package com.ukefu.webim.web.handler.apps.contacts;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ukefu.core.UKDataContext;
import com.ukefu.core.UKDataContext.EsTable;
import com.ukefu.util.Menu;
import com.ukefu.util.PinYinTools;
import com.ukefu.util.UKTools;
import com.ukefu.util.callout.CallOutUtils;
import com.ukefu.util.es.SearchTools;
import com.ukefu.util.es.UKDataBean;
import com.ukefu.util.task.DSData;
import com.ukefu.util.task.DSDataEvent;
import com.ukefu.util.task.ExcelImportProecess;
import com.ukefu.util.task.export.ExcelExporterProcess;
import com.ukefu.util.task.process.ContactsProcess;
import com.ukefu.webim.service.es.ContactsRepository;
import com.ukefu.webim.service.es.OrdersCommentRepository;
import com.ukefu.webim.service.es.WorkOrdersRepository;
import com.ukefu.webim.service.repository.AgentServiceRepository;
import com.ukefu.webim.service.repository.AgentUserContactsRepository;
import com.ukefu.webim.service.repository.AttachmentRepository;
import com.ukefu.webim.service.repository.CallOutNamesHisRepository;
import com.ukefu.webim.service.repository.ContactsItemAuthorizeRepository;
import com.ukefu.webim.service.repository.ContactsItemRepository;
import com.ukefu.webim.service.repository.ContactsRelationRepository;
import com.ukefu.webim.service.repository.JobDetailRepository;
import com.ukefu.webim.service.repository.MetadataRepository;
import com.ukefu.webim.service.repository.OrganRepository;
import com.ukefu.webim.service.repository.PropertiesEventRepository;
import com.ukefu.webim.service.repository.ReporterRepository;
import com.ukefu.webim.service.repository.SaleStatusRepository;
import com.ukefu.webim.service.repository.SaleStatusTypeRepository;
import com.ukefu.webim.service.repository.ServiceSummaryRepository;
import com.ukefu.webim.service.repository.StatusEventRepository;
import com.ukefu.webim.service.repository.TagRepository;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.util.CallCenterUtils;
import com.ukefu.webim.util.PropertiesEventUtils;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.AgentService;
import com.ukefu.webim.web.model.AgentServiceSummary;
import com.ukefu.webim.web.model.AgentUserContacts;
import com.ukefu.webim.web.model.AttachmentFile;
import com.ukefu.webim.web.model.CallOutNamesHis;
import com.ukefu.webim.web.model.Contacts;
import com.ukefu.webim.web.model.ContactsItem;
import com.ukefu.webim.web.model.ContactsItemAuthorize;
import com.ukefu.webim.web.model.ContactsItemExpress;
import com.ukefu.webim.web.model.ContactsItemTargetdis;
import com.ukefu.webim.web.model.ContactsRelation;
import com.ukefu.webim.web.model.DisTarget;
import com.ukefu.webim.web.model.FilterCriteria;
import com.ukefu.webim.web.model.JobDetail;
import com.ukefu.webim.web.model.JobTask;
import com.ukefu.webim.web.model.MetadataTable;
import com.ukefu.webim.web.model.OrdersComment;
import com.ukefu.webim.web.model.Organ;
import com.ukefu.webim.web.model.PropertiesEvent;
import com.ukefu.webim.web.model.SaleStatus;
import com.ukefu.webim.web.model.SaleStatusType;
import com.ukefu.webim.web.model.StatusEvent;
import com.ukefu.webim.web.model.SysDic;
import com.ukefu.webim.web.model.UKeFuDic;
import com.ukefu.webim.web.model.User;

@Controller
@RequestMapping("/apps/contacts")
public class ContactsController extends Handler{
	
	@Autowired
	private ContactsRepository contactsRes ;
	
	
	@Autowired
	private PropertiesEventRepository propertiesEventRes ;
	
	@Autowired
	private ReporterRepository reporterRes ;
	
	@Autowired
	private MetadataRepository metadataRes ;
	
	@Autowired
	private AgentUserContactsRepository agentUserContactsRes; 
	
	@Autowired
	private ContactsItemRepository contactsItemRes ;
	
	@Autowired
	private ContactsItemAuthorizeRepository contactsItemAuthorizeRes ;
	
	@Autowired
	private OrganRepository organRes ;	//查询部门
	
	@Autowired
	private UserRepository userRes;
	
	@Autowired
	private AgentServiceRepository agentServiceRepository;
	
	@Autowired
	private StatusEventRepository statusEventRes ;
	
	@Autowired
	private TagRepository tagRes ;
	
	@Autowired
	private ServiceSummaryRepository serviceSummaryRes ;
	
	@Autowired
	private CallOutNamesHisRepository callOutNamesHisRes ;
	
	@Autowired
	private JobDetailRepository jobRes ;
	
	@Autowired
	private ContactsRelationRepository contactsRelationRes;
	
	@Autowired
	private SaleStatusRepository saleStatusRes; //状态
	
	@Autowired
	private SaleStatusTypeRepository saleStatusTypeRes; //状态分类
	
	@Autowired
	private OrdersCommentRepository ordersCommentRes ;
	
	@Autowired
	private AttachmentRepository attachementRes;
	
	@Value("${web.upload-path}")
    private String path;
	
	@Autowired
	private WorkOrdersRepository workOrdersRes ;
	
    @RequestMapping("/index")
    @Menu(type = "contacts" , subtype = "index" ,name="index")
    public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String typename ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	if(!StringUtils.isBlank(typename)){
    		map.put("typename", typename) ;
    	}
    	map.put("nowUrl", "/apps/contacts/index") ;
    	return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    public BoolQueryBuilder doIndex(ModelMap map , HttpServletRequest request , String q , String ckind, String itemid,FilterCriteria filterCriteria ,String contactstype) {
    	if(!StringUtils.isBlank(contactstype)){
    		map.addAttribute("contactstype", contactstype);
    	}else{
    		map.addAttribute("contactstype", "index");
    		contactstype = "index";
    	}
    	map.addAttribute("userList", userRes.findByOrgi(super.getOrgi(request)));
    	
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	if(!StringUtils.isBlank(q)){
			q = q.replaceAll("(OR|AND|NOT|:|\\(|\\))", "") ;
			boolQueryBuilder.must(QueryBuilders.boolQuery().must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND))) ;
        	map.put("q", q) ;
        	filterCriteria.setQ(q);
        }
    	if(!StringUtils.isBlank(ckind) && !ckind.equals("null")){
    		boolQueryBuilder.must(termQuery("ckind" , ckind)) ;
    		filterCriteria.setCkind(ckind);
        	map.put("ckind", ckind) ;
        	map.put("ckinddic", UKeFuDic.getInstance().getDicItem(ckind)) ;
        }
    	
    	//得到有权限的项目
    	List<ContactsItem> contactsItemList = getContactsItem(super.getUser(request),super.getOrgi(request)) ;
    	map.addAttribute("contactsItemList", contactsItemList) ;
    	boolean isSup = false;
    	String statusCode = null;
    	if(!StringUtils.isBlank(itemid) && !itemid.equals("null")){
    		ContactsItem contactsItem = contactsItemRes.findByIdAndOrgi(itemid, super.getOrgi(request)) ;
    		if (contactsItem != null) {
				boolQueryBuilder.must(termQuery("itemid",contactsItem.getId()));
				ContactsItemAuthorize authorize = contactsItemAuthorizeRes.findByItemidAndUseridAndOrgiAndDatastatus(itemid, super.getUser(request).getId(), super.getOrgi(request),false);
				if ((authorize != null && authorize.isSup()) || contactsItem.getCreater().equals(super.getUser(request).getId())) {
					map.addAttribute("isSup",true);
					isSup = true;
				}
				statusCode = contactsItem.getStatuscode();
			}
        	map.addAttribute("contactsItem", contactsItem);
        	map.put("itemid", itemid) ;
        	filterCriteria.setItemid(itemid);
        }else {
//        	boolQueryBuilder.mustNot(QueryBuilders.wildcardQuery("itemid", "*"));
        	if(!StringUtils.isBlank(request.getParameter("searchitemid"))) {
        		boolQueryBuilder.must(termQuery("itemid", request.getParameter("searchitemid"))) ;
        		map.put("searchitemid", request.getParameter("searchitemid")) ;
        		filterCriteria.setSearchitemid(request.getParameter("searchitemid"));
        	}else {
        		filterCriteria.setMyall(super.getUser(request).getId());
        		if("index".equals(contactstype)){
        			boolQueryBuilder.mustNot(QueryBuilders.boolQuery()
        					.must(QueryBuilders.existsQuery("itemid"))
        					.must(QueryBuilders.wildcardQuery("itemid", "*")));
        		}else{
        			boolQueryBuilder.must(new BoolQueryBuilder().should(termQuery("creater", super.getUser(request).getId())).should(termQuery("owneruser", super.getUser(request).getId()))) ;
        		}
			}
		}
    	if (StringUtils.isBlank(statusCode)) {
			List<SysDic> sysDicList = UKeFuDic.getInstance().getDic("com.dic.callout.activity");
			if (sysDicList!= null && sysDicList.size() > 0 && sysDicList.get(0)!=null) {
				statusCode = sysDicList.get(0).getId();
			}
		}
    	List<SaleStatusType> saleStatusTypeList = saleStatusTypeRes.findByOrgiAndActivityid(super.getOrgi(request),statusCode);
		map.addAttribute("saleStatusTypeList", saleStatusTypeList);
		map.put("statusCode", statusCode);
		List<SaleStatus> saleStatusList = saleStatusRes.findByOrgiAndActivityid(super.getOrgi(request), statusCode) ;
		map.addAttribute("saleStatusList", saleStatusList);
    	if (!isSup && !super.getUser(request).isSuperuser() && (!StringUtils.isBlank(itemid)|| (!StringUtils.isBlank(request.getParameter("searchitemid"))))) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(termQuery("creater", super.getUser(request).getId())).should(termQuery("owneruser", super.getUser(request).getId()))) ;
		}
    	if ( !StringUtils.isBlank(itemid)) {
    		List<ContactsItemAuthorize> contactsItemAuthorizeList = contactsItemAuthorizeRes.findByItemidAndOrgiAndDatastatus(itemid, super.getOrgi(request),false);
    		List<String> useridList = new ArrayList<String>();
    		User user = userRes.findBySuperuser(true) ;
    		useridList.add(user.getId());
    		for(ContactsItemAuthorize authorize : contactsItemAuthorizeList) {
    			if (!useridList.contains(authorize.getUserid()) ) {
    				useridList.add(authorize.getUserid());
    			}
    		}
    		map.addAttribute("userAuthorizeList", userRes.findByIdInAndOrgiAndDatastatus(useridList, super.getOrgi(request),false));
		}
    	
    	//搜索条件
    	if(!StringUtils.isBlank(request.getParameter("name"))) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("name",request.getParameter("name"))).should(QueryBuilders.wildcardQuery("name","*"+request.getParameter("name")+"*"))) ;
			map.put("name", request.getParameter("name")) ;
			filterCriteria.setName(request.getParameter("name"));
		}
    	if(!StringUtils.isBlank(request.getParameter("creater"))) {
    		boolQueryBuilder.must(termQuery("creater", request.getParameter("creater"))) ;
			map.put("creater", request.getParameter("creater")) ;
			filterCriteria.setCreater(request.getParameter("creater"));
		}
    	if(!StringUtils.isBlank(request.getParameter("ckinds"))) {
    		boolQueryBuilder.must(termQuery("ckind", request.getParameter("ckinds"))) ;
			map.put("ckinds", request.getParameter("ckinds")) ;
			filterCriteria.setCkinds(request.getParameter("ckinds"));
		}
    	if(!StringUtils.isBlank(request.getParameter("gender"))) {
    		boolQueryBuilder.must(termQuery("gender", request.getParameter("gender"))) ;
			map.put("gender", request.getParameter("gender")) ;
			filterCriteria.setGender(request.getParameter("gender"));
		}
    	if(!StringUtils.isBlank(request.getParameter("phone"))) {
    		boolQueryBuilder.must(termQuery("phone", request.getParameter("phone"))) ;
			map.put("phone", request.getParameter("phone")) ;
			filterCriteria.setPhone(request.getParameter("phone"));
		}
    	if(!StringUtils.isBlank(request.getParameter("mobileno"))) {
    		boolQueryBuilder.must(termQuery("mobileno", request.getParameter("mobileno"))) ;
			map.put("mobileno", request.getParameter("mobileno")) ;
			filterCriteria.setMobileno(request.getParameter("mobileno"));
		}
    	if(!StringUtils.isBlank(request.getParameter("email"))) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("email",request.getParameter("email"))).should(QueryBuilders.wildcardQuery("email","*"+request.getParameter("email")+"*"))) ;
			map.put("email", request.getParameter("email")) ;
			filterCriteria.setEmail(request.getParameter("email"));
		}
    	if(!StringUtils.isBlank(request.getParameter("address"))) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("address",request.getParameter("address"))).should(QueryBuilders.wildcardQuery("address","*"+request.getParameter("address")+"*"))) ;
			map.put("address", request.getParameter("address")) ;
			filterCriteria.setAddress(request.getParameter("address"));
		}
    	if(!StringUtils.isBlank(request.getParameter("province"))) {
    		boolQueryBuilder.must(termQuery("province", request.getParameter("province"))) ;
			map.put("province", request.getParameter("province")) ;
			filterCriteria.setProvince(request.getParameter("province"));
		}
    	if(!StringUtils.isBlank(request.getParameter("city"))) {
    		boolQueryBuilder.must(termQuery("city", request.getParameter("city"))) ;
    		map.put("city", request.getParameter("city")) ;
    		filterCriteria.setCity(request.getParameter("city"));
    	}
    	if(!StringUtils.isBlank(request.getParameter("ctype"))) {
    		boolQueryBuilder.must(termQuery("ctype", request.getParameter("ctype"))) ;
    		map.put("ctype", request.getParameter("ctype")) ;
    		filterCriteria.setCtype(request.getParameter("ctype"));
    	}
    	if(!StringUtils.isBlank(request.getParameter("business"))) {
    		boolQueryBuilder.must(termQuery("business", request.getParameter("business"))) ;
    		map.put("business", request.getParameter("business")) ;
    		filterCriteria.setBusiness(request.getParameter("business"));
    	}
    	if(!StringUtils.isBlank(request.getParameter("busmemo"))) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("busmemo",request.getParameter("busmemo"))).should(QueryBuilders.wildcardQuery("busmemo","*"+request.getParameter("busmemo")+"*"))) ;
			map.put("busmemo", request.getParameter("busmemo")) ;
    		filterCriteria.setBusmemo(request.getParameter("busmemo"));
    	}
    	
    	//客户
    	if(!StringUtils.isBlank(request.getParameter("cusname"))) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("cusname",request.getParameter("cusname"))).should(QueryBuilders.wildcardQuery("cusname","*"+request.getParameter("cusname")+"*"))) ;
			map.put("cusname", request.getParameter("cusname")) ;
			filterCriteria.setCusname(request.getParameter("cusname"));
		}
    	if(!StringUtils.isBlank(request.getParameter("cusphone"))) {
    		boolQueryBuilder.must(termQuery("cusphone", request.getParameter("cusphone"))) ;
			map.put("cusphone", request.getParameter("cusphone")) ;
			filterCriteria.setCusphone(request.getParameter("cusphone"));
		}
    	if(!StringUtils.isBlank(request.getParameter("cusemail"))) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("cusemail",request.getParameter("cusemail"))).should(QueryBuilders.wildcardQuery("cusemail","*"+request.getParameter("cusemail")+"*"))) ;
			map.put("cusemail", request.getParameter("cusemail")) ;
			filterCriteria.setCusemail(request.getParameter("email"));
		}
    	if(!StringUtils.isBlank(request.getParameter("cusprovince"))) {
    		boolQueryBuilder.must(termQuery("cusprovince", request.getParameter("cusprovince"))) ;
			map.put("cusprovince", request.getParameter("cusprovince")) ;
			filterCriteria.setCusprovince(request.getParameter("cusprovince"));
		}
    	if(!StringUtils.isBlank(request.getParameter("cuscity"))) {
    		boolQueryBuilder.must(termQuery("cuscity", request.getParameter("cuscity"))) ;
    		map.put("cuscity", request.getParameter("cuscity")) ;
    		filterCriteria.setCuscity(request.getParameter("cuscity"));
    	}
    	if(!StringUtils.isBlank(request.getParameter("cusaddress"))) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("cusaddress",request.getParameter("cusaddress"))).should(QueryBuilders.wildcardQuery("cusaddress","*"+request.getParameter("cusaddress")+"*"))) ;
			map.put("cusaddress", request.getParameter("cusaddress")) ;
			filterCriteria.setCusaddress(request.getParameter("cusaddress"));
		}
    	if(!StringUtils.isBlank(request.getParameter("ekind"))) {
    		boolQueryBuilder.must(termQuery("ekind", request.getParameter("ekind"))) ;
			map.put("ekind", request.getParameter("ekind")) ;
			filterCriteria.setEkind(request.getParameter("ekind"));
		}
    	if(!StringUtils.isBlank(request.getParameter("elevel"))) {
    		boolQueryBuilder.must(termQuery("ekind", request.getParameter("elevel"))) ;
			map.put("elevel", request.getParameter("elevel")) ;
			filterCriteria.setElevel(request.getParameter("elevel"));
		}
    	if(!StringUtils.isBlank(request.getParameter("esource"))) {
    		boolQueryBuilder.must(termQuery("ekind", request.getParameter("esource"))) ;
			map.put("esource", request.getParameter("esource")) ;
			filterCriteria.setEsource(request.getParameter("esource"));
		}
    	if(!StringUtils.isBlank(request.getParameter("maturity"))) {
    		boolQueryBuilder.must(termQuery("maturity", request.getParameter("maturity"))) ;
			map.put("maturity", request.getParameter("maturity")) ;
			filterCriteria.setMaturity(request.getParameter("maturity"));
		}
    	if(!StringUtils.isBlank(request.getParameter("industry"))) {
    		boolQueryBuilder.must(termQuery("industry", request.getParameter("industry"))) ;
    		map.put("industry", request.getParameter("industry")) ;
    		filterCriteria.setIndustry(request.getParameter("industry"));
    	}
    	if(!StringUtils.isBlank(request.getParameter("cusvalidstatus"))) {
    		boolQueryBuilder.must(termQuery("cusvalidstatus", request.getParameter("cusvalidstatus"))) ;
    		map.put("cusvalidstatus", request.getParameter("cusvalidstatus")) ;
    		filterCriteria.setCusvalidstatus(request.getParameter("cusvalidstatus"));
    	}
    	if(!StringUtils.isBlank(request.getParameter("salestatus"))) {
    		boolQueryBuilder.must(termQuery("salestatus", request.getParameter("salestatus"))) ;
    		map.put("salestatus", request.getParameter("salestatus")) ;
    		filterCriteria.setSalestatus(request.getParameter("salestatus"));
    		SaleStatus saleStatus = saleStatusRes.findByIdAndOrgi(request.getParameter("salestatus"), super.getOrgi(request));
	    	map.addAttribute("currsaleStatus", saleStatus);
    	}
    	
    	if(!StringUtils.isBlank(request.getParameter("reservation"))) {
    		boolQueryBuilder.must(termQuery("reservation", request.getParameter("reservation").equals("1")?true:false)) ;
    		map.put("reservation", request.getParameter("reservation")) ;
    		filterCriteria.setReservation(request.getParameter("reservation"));
    	}
    	if(!StringUtils.isBlank(request.getParameter("reservtype"))) {
    		boolQueryBuilder.must(termQuery("reservtype", request.getParameter("reservtype"))) ;
    		map.put("reservtype", request.getParameter("reservtype")) ;
    		filterCriteria.setReservtype(request.getParameter("reservtype"));
    	}
    	
    	if(!StringUtils.isBlank(request.getParameter("salesmemo"))) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("salesmemo",request.getParameter("salesmemo"))).should(QueryBuilders.wildcardQuery("salesmemo","*"+request.getParameter("salesmemo")+"*"))) ;
    		map.put("salesmemo", request.getParameter("salesmemo")) ;
    		filterCriteria.setSalesmemo(request.getParameter("salesmemo"));
    	}
    	if(!StringUtils.isBlank(request.getParameter("updateuser"))) {
    		boolQueryBuilder.must(termQuery("updateuser", request.getParameter("updateuser"))) ;
    		map.put("updateuser", request.getParameter("updateuser")) ;
    		filterCriteria.setUpdateuser(request.getParameter("updateuser"));
    	}
    	if(!StringUtils.isBlank(request.getParameter("owneruser"))) {
    		boolQueryBuilder.must(termQuery("owneruser", request.getParameter("owneruser"))) ;
    		map.put("owneruser", request.getParameter("owneruser")) ;
    		filterCriteria.setUpdateuser(request.getParameter("owneruser"));
    	}
    	if(!StringUtils.isBlank(request.getParameter("weixin"))) {
    		boolQueryBuilder.must(termQuery("weixin", request.getParameter("weixin"))) ;
    		map.put("weixin", request.getParameter("weixin")) ;
    		filterCriteria.setWeixin(request.getParameter("weixin"));
    	}
    	
    	RangeQueryBuilder rangeQuery = null ;
		//创建时间区间查询
		if(!StringUtils.isBlank(request.getParameter("touchtimebegin")) || !StringUtils.isBlank(request.getParameter("touchtimeend"))){
			if(!StringUtils.isBlank(request.getParameter("touchtimebegin"))) {
				filterCriteria.setTouchtimebegin(request.getParameter("touchtimebegin"));
				try {
					rangeQuery = QueryBuilders.rangeQuery("touchtime").from(UKTools.dateFormate.parse(request.getParameter("touchtimebegin")).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(request.getParameter("touchtimeend")) ) {
				filterCriteria.setTouchtimeend(request.getParameter("touchtimeend"));
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("touchtime").to(UKTools.dateFormate.parse(request.getParameter("touchtimeend")).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(request.getParameter("touchtimeend")).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			map.put("touchtimebegin", request.getParameter("touchtimebegin")) ;
			map.put("touchtimeend", request.getParameter("touchtimeend")) ;
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
		rangeQuery = null ;
		if(!StringUtils.isBlank(request.getParameter("incallbegin")) || !StringUtils.isBlank(request.getParameter("incallend"))){
			if(!StringUtils.isBlank(request.getParameter("incallbegin"))) {
				filterCriteria.setIncallbegin(request.getParameter("incallbegin"));
				rangeQuery = QueryBuilders.rangeQuery("incall").from(Long.parseLong(request.getParameter("incallbegin"))*1000) ;
			}
			if(!StringUtils.isBlank(request.getParameter("incallend")) ) {
				filterCriteria.setIncallend(request.getParameter("incallend"));
				if(rangeQuery == null) {
					rangeQuery = QueryBuilders.rangeQuery("incall").to(Long.parseLong(request.getParameter("incallend"))*1000) ;
				}else {
					rangeQuery.to(Long.parseLong(request.getParameter("incallend"))*1000) ;
				}
			}
			map.put("incallbegin", request.getParameter("incallbegin")) ;
			map.put("incallend", request.getParameter("incallend")) ;
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
		rangeQuery = null ;
		if(!StringUtils.isBlank(request.getParameter("optimebegin")) || !StringUtils.isBlank(request.getParameter("optimeend"))){
			if(!StringUtils.isBlank(request.getParameter("optimebegin"))) {
				filterCriteria.setOptimebegin(request.getParameter("optimebegin"));
				try {
					rangeQuery = QueryBuilders.rangeQuery("optime").from(UKTools.dateFormate.parse(request.getParameter("optimebegin")).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(request.getParameter("optimeend")) ) {
				filterCriteria.setOptimeend(request.getParameter("optimeend"));
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("optime").to(UKTools.dateFormate.parse(request.getParameter("optimeend")).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(request.getParameter("optimeend")).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			map.put("optimebegin", request.getParameter("optimebegin")) ;
			map.put("optimeend", request.getParameter("optimeend")) ;
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
		rangeQuery = null ;
		if(!StringUtils.isBlank(request.getParameter("updatetimebegin")) || !StringUtils.isBlank(request.getParameter("updatetimeend"))){
			if(!StringUtils.isBlank(request.getParameter("updatetimebegin"))) {
				filterCriteria.setUpdatetimebegin(request.getParameter("updatetimebegin"));
				try {
					rangeQuery = QueryBuilders.rangeQuery("updatetime").from(UKTools.dateFormate.parse(request.getParameter("updatetimebegin")).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(request.getParameter("updatetimeend")) ) {
				filterCriteria.setUpdatetimeend(request.getParameter("updatetimeend"));
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("updatetime").to(UKTools.dateFormate.parse(request.getParameter("updatetimeend")).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(request.getParameter("updatetimeend")).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			map.put("updatetimebegin", request.getParameter("updatetimebegin")) ;
			map.put("updatetimeend", request.getParameter("updatetimeend")) ;
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
		map.put("allUserList", userRes.findByOrgiAndDatastatus(super.getOrgi(request), false));
    	return boolQueryBuilder ;
	}
    
    public List<ContactsItem> getContactsItem(final User user,final String orgi) {
    	List<ContactsItem> allItemList = contactsItemRes.findByOrgiOrderByCreatetimeDesc(orgi);
    	if (user.isSuperuser()) {
			return allItemList ;
		}else {
			List<ContactsItem> contactsItemList = new ArrayList<ContactsItem>();
			List<ContactsItemAuthorize> authList = contactsItemAuthorizeRes.findByUseridAndOrgiAndDatastatus(user.getId(),orgi ,false) ;
			List<String> parentList = new ArrayList<String>();
			if (allItemList != null && allItemList.size() > 0) {
				for(ContactsItem item : allItemList) {
					if (item.getCreater().equals(user.getId())) {//自己创建的直接放入
						contactsItemList.add(item) ;
					}else {
						if (authList != null && authList.size() > 0) {//判断授权
							for(ContactsItemAuthorize authorize : authList) {
								if (item.getId().equals(authorize.getItemid()) && !item.getCreater().equals(user.getId())) {//若权限表有此项目且不是自己创建
									contactsItemList.add(item) ;//先把项目放入
									for(ContactsItem itemau : allItemList) {
										//判断是否有子项 || 判断是否有父级
										if ((!StringUtils.isBlank(itemau.getParentid()) && !item.getCreater().equals(user.getId()) && item.getId().equals(itemau.getParentid())) || (!StringUtils.isBlank(item.getParentid()) && !item.getCreater().equals(user.getId()) && itemau.getId().equals(item.getParentid()))) {
											if (!parentList.contains(itemau.getId())) {
												parentList.add(itemau.getId());
												contactsItemList.add(itemau) ;//有放入
											}
										}
									}
								}
							}
						}
					}
				}
			}
			parentList.clear();
			parentList = null;
			return contactsItemList ;
		}
	}
    
    @RequestMapping("/today")
    @Menu(type = "contacts" , subtype = "today", name = "today")
    public ModelAndView today(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request),UKTools.getStartTime() , null , false, this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	filterCriteria.setToday(true);
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("nowUrl", "/apps/contacts/today") ;
    	return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/week")
    @Menu(type = "contacts" , subtype = "week", name = "week")
    public ModelAndView week(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), UKTools.getWeekStartTime() , null , false, this.doIndex(map, request, q, ckind, itemid,filterCriteria,contactstype) ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	filterCriteria.setWeek(true);
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("nowUrl", "/apps/contacts/week") ;
    	return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/my")
    @Menu(type = "contacts" , subtype = "my",name="my")
    public ModelAndView my(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	filterCriteria.setMyall(super.getUser(request).getId());
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ;
    	boolQueryBuilder.must(new BoolQueryBuilder().should(termQuery("creater", super.getUser(request).getId())).should(termQuery("owneruser", super.getUser(request).getId()))) ;
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("nowUrl", "/apps/contacts/my") ;
        return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/notcall")
    @Menu(type = "contacts" , subtype = "notcall",name="notcall")
    public ModelAndView notcall(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ;
    	filterCriteria.setNotcall(true);
    	boolQueryBuilder.mustNot(termQuery("callstatus",UKDataContext.NameStatusTypeEnum.CALLED.toString())) ;
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("contactstype", contactstype) ;
    	map.put("nowUrl", "/apps/contacts/notcall") ;
        return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/called")
    @Menu(type = "contacts" , subtype = "called",name="called")
    public ModelAndView called(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ;
    	filterCriteria.setCalled(true);
    	boolQueryBuilder.must(termQuery("callstatus",UKDataContext.NameStatusTypeEnum.CALLED.toString())) ;
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("contactstype", contactstype) ;
    	map.put("nowUrl", "/apps/contacts/called") ;
        return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/callsuccess")
    @Menu(type = "contacts" , subtype = "callsuccess",name="callsuccess")
    public ModelAndView callsuccess(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ;
    	filterCriteria.setCallsuccess(true);
    	boolQueryBuilder.must(termQuery("callstatus",UKDataContext.NameStatusTypeEnum.CALLED.toString())) ;
    	boolQueryBuilder.must(termQuery("workstatus", UKDataContext.NamesCalledEnum.SUCCESS.toString())) ;
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("contactstype", contactstype) ;
    	map.put("nowUrl", "/apps/contacts/callsuccess") ;
        return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/notdis")
    @Menu(type = "contacts" , subtype = "notdis",name="notdis")
    public ModelAndView notdis(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ;
    	filterCriteria.setNotdis(true);
    	boolQueryBuilder.mustNot(termQuery("status", UKDataContext.NamesDisStatusType.DISAGENT.toString())) ;
    	boolQueryBuilder.mustNot(termQuery("status", UKDataContext.NamesDisStatusType.DISORGAN.toString())) ;
    	boolQueryBuilder.mustNot(termQuery("status", UKDataContext.NamesDisStatusType.DISAI.toString())) ;
    	boolQueryBuilder.mustNot(termQuery("status", UKDataContext.NamesDisStatusType.DISFORECAST.toString())) ;
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("nowUrl", "/apps/contacts/notdis") ;
        return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
        
    @RequestMapping("/disagent")
    @Menu(type = "contacts" , subtype = "disagent",name="disagent")
    public ModelAndView disagent(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	filterCriteria.setDisagent(super.getUser(request).getId());
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ;
    	filterCriteria.setStatus(UKDataContext.NamesDisStatusType.DISAGENT.toString());
    	boolQueryBuilder.must(termQuery("status", UKDataContext.NamesDisStatusType.DISAGENT.toString())) ;
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("contactstype", contactstype) ;
    	map.put("nowUrl", "/apps/contacts/disagent") ;
        return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/disview")
    @Menu(type = "contacts" , subtype = "disview",name="disview")
    public ModelAndView disview(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String contactstype) {
    	BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
    	boolQueryBuilder.must(termQuery("datastatus","false" ));
    	if (!StringUtils.isBlank(itemid)) {
    		boolQueryBuilder.must(termQuery("itemid",itemid ));
		}
    	if (!StringUtils.isBlank(ckind) && !"null".equals(ckind)) {
    		boolQueryBuilder.must(termQuery("ckind",ckind ));
    		map.put("ckind", ckind) ;
    	}
    	PageImpl<UKDataBean> aggregation = SearchTools.aggregationContacts(super.search(boolQueryBuilder, map, request),
    			UKDataContext.UKEFU_SYSTEM_DIS_AGENT, true, super.getP(request), 10000);
    	map.addAttribute("aggregationList", aggregation);
    	map.put("allUserList", userRes.findByOrgiAndDatastatus(super.getOrgi(request), false));
    	List<ContactsItem> contactsItemList = getContactsItem(super.getUser(request),super.getOrgi(request)) ;
    	map.addAttribute("contactsItemList", contactsItemList) ;
    	
    	if(!StringUtils.isBlank(itemid) && !itemid.equals("null")){
    		ContactsItem contactsItem = contactsItemRes.findByIdAndOrgi(itemid, super.getOrgi(request)) ;
    		if (contactsItem != null) {
				ContactsItemAuthorize authorize = contactsItemAuthorizeRes.findByItemidAndUseridAndOrgiAndDatastatus(itemid, super.getUser(request).getId(), super.getOrgi(request),false);
				if ((authorize != null && authorize.isSup()) || contactsItem.getCreater().equals(super.getUser(request).getId())) {
					map.addAttribute("isSup",true);
				}
			}
        	map.addAttribute("contactsItem", contactsItem);
        	map.put("itemid", itemid) ;
        }
    	map.put("contactstype", contactstype) ;
    	return request(super.createAppsTempletResponse("/apps/business/contacts/indexdis"));
    }
    
    @RequestMapping("/disview/recycle")
    @Menu(type = "contacts" , subtype = "disview",name="disview")
    public ModelAndView disviewrecycle(ModelMap map , HttpServletRequest request , @Valid String itemid, @Valid String ckind ,@Valid String owneruser,@Valid String p,@Valid String contactstype) {
    	BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
    	if (!StringUtils.isBlank(itemid)) {
    		boolQueryBuilder.must(termQuery("itemid",itemid ));
		}
    	if (!StringUtils.isBlank(ckind) && !"null".equals(ckind)) {
    		boolQueryBuilder.must(termQuery("ckind",ckind ));
    	}
    	if (!StringUtils.isBlank(owneruser)) {
    		boolQueryBuilder.must(termQuery("owneruser",owneruser ));
    	}
    	Page<Contacts> contactsPage = contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,null , new PageRequest(0 , 10000));
    	if (contactsPage != null && contactsPage.getContent().size() > 0 ) {
			List<Contacts> contactsList = new ArrayList<Contacts>();
			for(Contacts contacts : contactsPage.getContent()) {
				contacts.setOwneruser(null);
				contacts.setOwnerdept(null);
				contacts.setDistime(null);
				contacts.setCallstatus(null);
				contacts.setStatus(null);
				contactsList.add(contacts);
			}
			if (contactsList != null && contactsList.size() > 0) {
				contactsRes.save(contactsList) ;
			}
		}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/disview.html?p="+p+"&ckind="+ckind+"&itemid="+itemid+"&contactstype="+contactstype));
    }
    
    @RequestMapping("/disorgan")
    @Menu(type = "contacts" , subtype = "disorgan",name="disorgan")
    public ModelAndView disorgan(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	filterCriteria.setDisorgan(super.getUser(request).getOrgan());
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ;
    	if(super.getUser(request).getOrgan() != null){
    		boolQueryBuilder.must(termQuery("ownerdept", super.getUser(request).getOrgan())) ;
    	}
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("organ", super.getUser(request).getOrgan()) ;
    	map.put("nowUrl", "/apps/contacts/disorgan") ;
        return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/wasted")
    @Menu(type = "contacts" , subtype = "wasted",name="wasted")
    public ModelAndView wasted(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	filterCriteria.setStatus(UKDataContext.NamesDisStatusType.WASTE.toString());
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ;
    	boolQueryBuilder.must(termQuery("status", UKDataContext.NamesDisStatusType.WASTE.toString())) ;
    	
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("nowUrl", "/apps/contacts/wasted") ;
    	return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/reserved")
    @Menu(type = "contacts" , subtype = "reserved",name="reserved")
    public ModelAndView reserved(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ;
    	filterCriteria.setReserved(true);
    	boolQueryBuilder.must(termQuery("reservation", true)) ;
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("contactstype", contactstype) ;
    	map.put("nowUrl", "/apps/contacts/reserved") ;
        return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/delete")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView delete(HttpServletRequest request ,@Valid Contacts contacts ,@Valid String p,@Valid String ckind,@Valid String itemid) {
    	if(contacts!=null){
    		contacts = contactsRes.findByIdAndOrgi(contacts.getId(),super.getOrgi(request)) ;
    		contacts.setDatastatus(true);							//客户和联系人都是 逻辑删除
    		contactsRes.save(contacts) ;
    		List<AgentUserContacts> agentUserContactsList = agentUserContactsRes.findByContactsidAndOrgi(contacts.getId(), super.getOrgi(request)) ;
    		agentUserContactsRes.delete(agentUserContactsList);
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html?p="+p+"&ckind="+ckind+"&itemid="+itemid));
    }
    
    @RequestMapping("/add")
    @Menu(type = "contacts" , subtype = "add")
    public ModelAndView add(ModelMap map , HttpServletRequest request,@Valid String ckind,@Valid String itemid) {
    	map.addAttribute("itemid",itemid);
    	map.addAttribute("ckind",ckind);

		map.put("organList", organRes.findByOrgi(super.getOrgi(request))) ;

        return request(super.createRequestPageTempletResponse("/apps/business/contacts/add"));
    }
    
    @RequestMapping(  "/save")
    @Menu(type = "contacts" , subtype = "save")
    public ModelAndView save(HttpServletRequest request  , @Valid Contacts contacts) {
		contacts.setCreater(super.getUser(request).getId());
		contacts.setOrgi(super.getOrgi(request));
		contacts.setOrgan(super.getUser(request).getOrgan());
		contacts.setPinyin(PinYinTools.getInstance().getFirstPinYin(contacts.getName()));
		if(StringUtils.isBlank(contacts.getCbirthday())) {
			contacts.setCbirthday(null);
		}else {
			contacts.setCbirthday(contacts.getCbirthday());
		}
		contacts.setCreatetime(new Date());
		this.setContactsDicDetails(request, contacts);
		contactsRes.save(contacts) ;
		String reqString = !StringUtils.isBlank(contacts.getItemid())?"?itemid="+contacts.getItemid():!StringUtils.isBlank(contacts.getCkind())?"?ckind="+contacts.getCkind():"" ;
		return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html"+reqString));
    }
    
    //查询联系人信息，查询当前登录人有权限的项目下拉项
    public void searchContactsItemList(ModelMap map ,String id, HttpServletRequest request){
    	Contacts contacts = contactsRes.findByIdAndOrgi(id,super.getOrgi(request));
    	if(contacts != null){
    		map.addAttribute("contacts", contacts) ;
    		List<ContactsItem> resultList = new ArrayList<ContactsItem>();
    		List<ContactsItem> contactsItemList = getContactsItem(super.getUser(request),super.getOrgi(request));
    		if(!contactsItemList.isEmpty()){
    			for(ContactsItem contactsItem :contactsItemList){
    				List<ContactsItem> dataList = contactsItemRes.findByParentidAndOrgi(contactsItem.getId(), super.getOrgi(request));
    				if(!dataList.isEmpty()){
    					resultList.addAll(dataList);
    				}
    			}
    		}
    		map.addAttribute("contactsItemList", resultList) ;


			if (!StringUtils.isBlank(contacts.getCusorgan()) && !"0".equals(contacts.getCusorgan())) {
				map.put("organData", organRes.findById(contacts.getCusorgan())) ;
			}
			map.put("organList", organRes.findByOrgi(super.getOrgi(request))) ;
    	}
    }
    
    @RequestMapping("/edit")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView edit(ModelMap map , HttpServletRequest request , @Valid String id,@Valid String ckind,@Valid String itemid,@Valid String p ,@Valid String contactstype ,@Valid String nowUrl) {
    	
    	this.searchContactsItemList(map, id, request);
    	map.addAttribute("type", itemid) ;
    	map.addAttribute("ckind",ckind);
    	map.addAttribute("p",p);
    	map.addAttribute("contactstype",contactstype);
    	map.addAttribute("nowUrl",nowUrl);


    	
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/edit"));
    }
    
    @RequestMapping("/partial/edit")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView editPartial(ModelMap map , HttpServletRequest request , @Valid String id,@Valid String ckind,@Valid String itemid,@Valid String p ,@Valid String contactstype ,@Valid String nowUrl) {
    	this.searchContactsItemList(map, id, request);
    	map.addAttribute("type", itemid) ;
    	map.addAttribute("ckind",ckind);
    	map.addAttribute("p",p);
    	map.addAttribute("contactstype",contactstype);
    	map.addAttribute("nowUrl",nowUrl);
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/partialedit"));
    }
    
    @RequestMapping( "/partial/update")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView updatePartial(ModelMap map ,HttpServletRequest request  , @Valid final Contacts contacts,@Valid String type,@Valid String p ,@Valid String contactstype ,@Valid String nowUrl) {
    	Contacts data = contactsRes.findByIdAndOrgi(contacts.getId(),super.getOrgi(request)) ;
    	this.setContactsDicDetails(request, contacts);
    	if(data!=null){
    		
    		this.updateContacts(contacts, data, request);
	    	contactsRes.save(data);
	    	
	    	map.addAttribute("contacts", data);
    		
	    	final String orgi = super.getOrgi(request);

    		ContactsItem contactsItem = contactsItemRes.findByIdAndOrgi(data.getItemid(), super.getOrgi(request)) ;
    		if (contactsItem != null) {
    			ContactsItemAuthorize authorize = contactsItemAuthorizeRes.findByItemidAndUseridAndOrgiAndDatastatus(contactsItem.getId(), super.getUser(request).getId(), super.getOrgi(request),false);
    			if ((authorize != null && authorize.isSup()) || contactsItem.getCreater().equals(super.getUser(request).getId())) {
    				map.addAttribute("isSup",true);
    			}
			}else {
				if (data.getCreater().equals(super.getUser(request).getId())) {
					map.addAttribute("isSup",true);
				}
			}
    		
    		map.addAttribute("contactsItem", contactsItem) ;
    		//关系联系人
    		List<ContactsRelation> contactsRelationList = contactsRelationRes.findByContactsidAndOrgi(contacts.getId(), super.getOrgi(request));
    		if (contactsRelationList != null && contactsRelationList.size() > 0) {
    			List<String> idsList = new ArrayList<String>();
				for(ContactsRelation relation : contactsRelationList) {
					idsList.add(relation.getRelateid()) ;
				}
				if (idsList != null) {
					BoolQueryBuilder boolQueryBuilder2 = new BoolQueryBuilder();
					BoolQueryBuilder boolQueryBuilder3 = new BoolQueryBuilder();
					for(String ids : idsList) {
						boolQueryBuilder3.should(termQuery("id", ids)) ;
					}
					boolQueryBuilder2.must(boolQueryBuilder3);
					Page<Contacts> conPage = contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder2 ,null , new PageRequest(super.getP(request) , super.getPs(request)));
					map.addAttribute("relcontactsList",conPage ) ;
					map.addAttribute("contactsRelationList",contactsRelationList ) ;
				}
			}
    		
    		//通话历史
    		map.addAttribute("statusEventHisList",statusEventRes.findAll(new Specification<StatusEvent>(){
				@Override
				public Predicate toPredicate(Root<StatusEvent> root, CriteriaQuery<?> query,
						CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<Predicate>();  
					list.add(cb.equal(root.get("orgi").as(String.class), orgi));
					list.add(cb.equal(root.get("contactsid").as(String.class), contacts.getId()));
					Predicate[] p = new Predicate[list.size()];  
					return cb.and(list.toArray(p));  
				}},new PageRequest(super.getP(request),super.getPs(request),Sort.Direction.DESC,new String[] {"createtime"})));
    		
    		//会话历史
			Page<AgentService> agentServiceList = agentServiceRepository.findAll(new Specification<AgentService>() {
				@Override
				public Predicate toPredicate(Root<AgentService> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<Predicate>();  
					list.add(cb.equal(root.get("orgi").as(String.class), orgi));
					list.add(cb.equal(root.get("contactsid").as(String.class), contacts.getId()));
					Predicate[] p = new Predicate[list.size()];  
					return cb.and(list.toArray(p));  
				}
			}, new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC,new String[] {"createtime"}));
			map.addAttribute("agentServiceList", agentServiceList);
			map.addAttribute("contactsModel", true);
			
			//服务小结
			List<AgentServiceSummary> summaryList = this.serviceSummaryRes.findByOrgiAndContactsid(super.getOrgi(request), contacts.getId());
			map.addAttribute("summaryList", summaryList) ;
			List<SysDic> reservtypeList = UKeFuDic.getInstance().getDic("com.dic.summary.reservtype");
			map.addAttribute("reservtypeList", reservtypeList);
			map.addAttribute("tags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.CCSUMMARY.toString())) ;
			
			//工单
			if(UKDataContext.model.get("workorders")!=null && workOrdersRes != null && !StringUtils.isBlank(contacts.getId())){
				if(workOrdersRes!=null){
					map.addAttribute("workOrdersList", workOrdersRes.findByCusidAndOrgi(contacts.getId(), super.getOrgi(request))) ;
				}
				map.addAttribute("contactsid", contacts.getId()) ;
			}
			//名单
			BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
			queryBuilder.must(termQuery("contactsid", contacts.getId()));
			PageImpl<UKDataBean> dataList = SearchTools.search(super.search(queryBuilder, map, request), super.getP(request),
					super.getPs(request));
			map.addAttribute("dataallList", dataList);
			if (dataList.getContent().size() > 0) {
				HashSet<String> metaIdList = new HashSet<>();
				for(UKDataBean bean : dataList.getContent()) {
					String name = bean.getType() ;
					if(!StringUtils.isBlank(name)) {
						name = (String) bean.getValues().get("metaid") ;
					}
					if(!StringUtils.isBlank(name)) {
						metaIdList.add(name);
					}
				}
				if(metaIdList.size() > 0) {
					List<String> metaList = new ArrayList<>();
					metaList.addAll(metaIdList);
					List<MetadataTable> tableList = metadataRes
							.findByTablenameIn(metaList);
					map.put("tableList", tableList);
				}
			}
			//营销记录
			Page<CallOutNamesHis> hisPage =callOutNamesHisRes.findByDataidAndOrgi( contacts.getId(),super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC, "createtime"));
			map.addAttribute("callOutNamesHisList", hisPage);
			map.addAttribute("userList", this.userRes.findByOrgiAndDatastatus(orgi, false));
			map.addAttribute("saleStatusList", saleStatusRes.findByOrgi(orgi));
		
    	}
    	 return request(super.createAppsTempletResponse("/apps/business/contacts/view"));
    }
    
    @RequestMapping("/detail")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView detail(ModelMap map , HttpServletRequest request , @Valid String id) {
    	map.addAttribute("contacts", contactsRes.findByIdAndOrgi(id,super.getOrgi(request))) ;
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/detail"));
    }
    
      
    @RequestMapping( "/update")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView update(HttpServletRequest request  , @Valid Contacts contacts,@Valid String type,@Valid String p ,@Valid String contactstype ,@Valid String nowUrl) {
    	Contacts data = contactsRes.findByIdAndOrgi(contacts.getId(),super.getOrgi(request)) ;
    	this.setContactsDicDetails(request, contacts);
    	if(data!=null){
    		
    		this.updateContacts(contacts, data, request);
	    	contactsRes.save(data);
    	}
        return request(super.createRequestPageTempletResponse("/public/success"));
    }
    
    @RequestMapping("/imp")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView imp(ModelMap map , HttpServletRequest request,@Valid String ckind,@Valid String itemid) {
//    	map.addAttribute("ckind",ckind);
    	map.addAttribute("itemid",itemid);
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/imp"));
    }
    
    @RequestMapping("/impsave")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView impsave(ModelMap map , HttpServletRequest request , @RequestParam(value = "cusfile", required = false) MultipartFile cusfile,@Valid String ckind,@Valid String itemid) throws IOException {
    	DSDataEvent event = new DSDataEvent();
    	String fileName = "contacts/"+UKTools.getUUID()+cusfile.getOriginalFilename().substring(cusfile.getOriginalFilename().lastIndexOf(".")) ;
    	File excelFile = new File(path , fileName) ;
    	if(!excelFile.getParentFile().exists()){
    		excelFile.getParentFile().mkdirs() ;
    	}
    	MetadataTable table = metadataRes.findByTablenameIgnoreCase("uk_contacts") ;
    	if(table!=null){
	    	FileUtils.writeByteArrayToFile(new File(path , fileName), cusfile.getBytes());
	    	event.setDSData(new DSData(table,excelFile , cusfile.getContentType(), super.getUser(request)));
	    	event.getDSData().setClazz(Contacts.class);
	    	event.getDSData().setProcess(new ContactsProcess(contactsRes));
	    	event.setOrgi(super.getOrgi(request));
	    	event.setTablename(EsTable.UK_CONTACTS.toString());
	    	if(!StringUtils.isBlank(ckind)){
	    		event.getValues().put("ckind", ckind) ;
	    	}
	    	if(!StringUtils.isBlank(itemid)){
	    		event.getValues().put("itemid", itemid) ;
	    	}
	    	event.getValues().put("creater", super.getUser(request).getId()) ;
	    	event.getValues().put("createtime", new Date());
	    	reporterRes.save(event.getDSData().getReport()) ;
	    	new ExcelImportProecess(event).process() ;		//启动导入任务
    	}
    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html?itemid="+itemid+"&ckind="+ckind));
    }
    
    @RequestMapping("/expids")
    @Menu(type = "contacts" , subtype = "contacts")
    public void expids(ModelMap map , HttpServletRequest request , HttpServletResponse response , @Valid String[] ids) throws IOException {
    	if(ids!=null && ids.length > 0){
    		Iterable<Contacts> contactsList = contactsRes.findByIdInAndOrgi(Arrays.asList(ids),super.getOrgi(request)) ;
    		MetadataTable table = metadataRes.findByTablenameIgnoreCase("uk_contacts") ;
    		List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
    		for(Contacts contacts : contactsList){
    			values.add(UKTools.transBean2Map(contacts)) ;
    		}
    		
    		response.setHeader("content-disposition", "attachment;filename=UCKeFu-Contacts-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");  
    		
    		ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
    		excelProcess.process();
    	}
    	
        return ;
    }
    
   @RequestMapping("/expall")
    @Menu(type = "contacts" , subtype = "contacts")
    public void expalls(ModelMap map , HttpServletRequest request , HttpServletResponse response,@Valid String ckind ,@Valid String itemid) throws IOException {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	boolQueryBuilder.must(termQuery("datastatus" , false)) ;		//只导出 数据删除状态 为 未删除的 数据
    	if(!StringUtils.isBlank(ckind)){
    		boolQueryBuilder.must(termQuery("ckind" , ckind)) ;
        }
    	if(!StringUtils.isBlank(itemid)){
    		boolQueryBuilder.must(termQuery("itemid" , itemid)) ;
        }
    	Iterable<Contacts> contactsList = contactsRes.findByQueryAndOrgi(null, super.getOrgi(request),null , null , false, boolQueryBuilder , null , new PageRequest(super.getP(request) , 10000));
    	
    	MetadataTable table = metadataRes.findByTablenameIgnoreCase("uk_contacts") ;
		List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
		for(Contacts contacts : contactsList){
			values.add(UKTools.transBean2Map(contacts)) ;
		}
		
		response.setHeader("content-disposition", "attachment;filename=UCKeFu-Contacts-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");  
		
		ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
		excelProcess.process();
        return ;
    }
    
     @RequestMapping("/expsearch")
    @Menu(type = "contacts" , subtype = "contacts")
    public void expall(ModelMap map , HttpServletRequest request , HttpServletResponse response , @Valid String q , @Valid String ekind,@Valid String filter) throws IOException {
    	Page<Contacts> temp = null;
    	if (!StringUtils.isBlank(filter)) {
    		String filterstr = UKTools.decode(filter.replaceAll(" ", "+"), String.class) ;
    		ObjectMapper objectMapper = new ObjectMapper();  
    		FilterCriteria filterCriteria = objectMapper.readValue(filterstr, FilterCriteria.class) ;
    		if(filterCriteria!=null) {
    			if (filterCriteria.isToday()) {
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), UKTools.getStartTime() , null , false, this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria) ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}else if (filterCriteria.isWeek()) {
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), UKTools.getWeekStartTime() , null , false, this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria) ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}else if (filterCriteria.isNotcall()) {
    				BoolQueryBuilder boolQueryBuilder = this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria);
    				boolQueryBuilder.mustNot(termQuery("callstatus",UKDataContext.NameStatusTypeEnum.CALLED.toString())) ;
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}else if (filterCriteria.isCalled()) {
    				BoolQueryBuilder boolQueryBuilder = this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria);
    				boolQueryBuilder.must(termQuery("callstatus",UKDataContext.NameStatusTypeEnum.CALLED.toString())) ;
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}else if (filterCriteria.isCallsuccess()) {
    				BoolQueryBuilder boolQueryBuilder = this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria);
    				boolQueryBuilder.must(termQuery("callstatus",UKDataContext.NameStatusTypeEnum.CALLED.toString())) ;
    		    	boolQueryBuilder.must(termQuery("workstatus", UKDataContext.NamesCalledEnum.SUCCESS.toString())) ;
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}else if (filterCriteria.isCallfaild()) {
    				BoolQueryBuilder boolQueryBuilder = this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria);
    				boolQueryBuilder.must(termQuery("callstatus",UKDataContext.NameStatusTypeEnum.CALLED.toString())) ;
    		    	boolQueryBuilder.must(termQuery("workstatus", UKDataContext.NamesCalledEnum.FAILD.toString())) ;
    		    	if(!StringUtils.isBlank(filterCriteria.getHangupcase())){
    	    			boolQueryBuilder.must(termQuery("hangupcase", filterCriteria.getHangupcase())) ;
    		    	}
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}else if (filterCriteria.isNotdis()) {
    				BoolQueryBuilder boolQueryBuilder = this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria);
    				boolQueryBuilder.mustNot(termQuery("status", UKDataContext.NamesDisStatusType.DISAGENT.toString())) ;
    		    	boolQueryBuilder.mustNot(termQuery("status", UKDataContext.NamesDisStatusType.DISORGAN.toString())) ;
    		    	boolQueryBuilder.mustNot(termQuery("status", UKDataContext.NamesDisStatusType.DISAI.toString())) ;
    		    	boolQueryBuilder.mustNot(termQuery("status", UKDataContext.NamesDisStatusType.DISFORECAST.toString())) ;
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}else if (!StringUtils.isBlank(filterCriteria.getDisagent())) {
    				BoolQueryBuilder boolQueryBuilder = this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria);
    				boolQueryBuilder.must(termQuery("status", UKDataContext.NamesDisStatusType.DISAGENT.toString())) ;
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}else if (!StringUtils.isBlank(filterCriteria.getDisorgan())) {
    				BoolQueryBuilder boolQueryBuilder = this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria);
    				boolQueryBuilder.must(termQuery("ownerdept", filterCriteria.getDisorgan())) ;
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}else if (filterCriteria.isReserved()) {
    				BoolQueryBuilder boolQueryBuilder = this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria);
    				boolQueryBuilder.must(termQuery("reservation", true)) ;
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}else {
    				temp = this.contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, this.doFilterSearch(filterCriteria.getQ(), filterCriteria.getCkind(), filterCriteria.getItemid(),filterCriteria) ,filterCriteria.getQ() , new PageRequest(0 , 10000)) ;
    			}
    		}
		}else {
			
		}
    	if(temp != null && temp.getTotalElements() > 0) {
    		MetadataTable table = metadataRes.findByTablenameIgnoreCase("uk_contacts") ;
        	List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
        	for(Contacts contacts : temp){
        		values.add(UKTools.transBean2Map(contacts)) ;
        	}

        	response.setHeader("content-disposition", "attachment;filename=UCKeFu-Contacts-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");  

        	ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
        	excelProcess.process();
		}
    	
        return ;
    }
    
    
    @RequestMapping("/embed/index")
    @Menu(type = "contacts" , subtype = "embed")
    public ModelAndView embed(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String ani) {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	if(!StringUtils.isBlank(q)){
        	map.put("q", q) ;
        }
    	if(!StringUtils.isBlank(ani)){
    		BoolQueryBuilder phoneBooleanQuery = QueryBuilders.boolQuery();
    		List<AgentUserContacts> agentUserContactsList = agentUserContactsRes.findByUseridAndOrgi(ani, super.getOrgi(request)) ;
    		if(agentUserContactsList != null && agentUserContactsList.size() > 0 && !org.apache.commons.lang3.StringUtils.isBlank(agentUserContactsList.get(0).getContactsid())) {
    			phoneBooleanQuery.should(termQuery("id" , agentUserContactsList.get(0).getContactsid())) ;
    		}
    		phoneBooleanQuery.should(termQuery("phone" , ani)) ;
    		phoneBooleanQuery.should(termQuery("mobilephone" , ani)) ;
    		boolQueryBuilder.must(phoneBooleanQuery) ;
        	map.put("ani", ani) ;
        }
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi( null,super.getOrgi(request),null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	
    	return request(super.createRequestPageTempletResponse("/apps/business/contacts/embed/index"));
    }
    
    @RequestMapping("/embed/add")
    @Menu(type = "contacts" , subtype = "embedadd")
    public ModelAndView embedadd(ModelMap map , HttpServletRequest request, @Valid String ani) {
    	if(!StringUtils.isBlank(ani)){
        	map.put("ani", ani) ;
        }
    	map.addAttribute("contactsItemList", getContactsItem(super.getUser(request),super.getOrgi(request))) ;
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/embed/add"));
    }
    
    @RequestMapping(  "/embed/save")
    @Menu(type = "contacts" , subtype = "embedsave")
    public ModelAndView embedsave(HttpServletRequest request  , @Valid Contacts contacts, @Valid String ani) {
		contacts.setCreater(super.getUser(request).getId());
		contacts.setOrgi(super.getOrgi(request));
		contacts.setOrgan(super.getUser(request).getOrgan());
		contacts.setPinyin(PinYinTools.getInstance().getFirstPinYin(contacts.getName()));
		if(StringUtils.isBlank(contacts.getCbirthday())) {
			contacts.setCbirthday(null);
		}
		this.setContactsDicDetails(request, contacts);
		contactsRes.save(contacts) ;
        return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/embed/index.html"+(!StringUtils.isBlank(ani) ? "?ani="+ani : null)));
    }
    
    @RequestMapping("/embed/edit")
    @Menu(type = "contacts" , subtype = "embededit")
    public ModelAndView embededit(ModelMap map , HttpServletRequest request , @Valid String id) {
    	this.searchContactsItemList(map, id, request);
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/embed/edit"));
    }
    
    @RequestMapping(  "/embed/update")
    @Menu(type = "contacts" , subtype = "embedupdate")
    public ModelAndView embedupdate(HttpServletRequest request  , @Valid Contacts contacts) {
    	Contacts data = contactsRes.findByIdAndOrgi(contacts.getId(),super.getOrgi(request)) ;
    	this.setContactsDicDetails(request, contacts);
    	if(data!=null){
    		
    		this.updateContacts(contacts, data, request);
	    	contactsRes.save(data);
    	}
    	
        return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/embed/index.html"));
    }
    
    @RequestMapping("/updatemapping")
    @ResponseBody
    public void updatemapping(ModelMap map , HttpServletRequest request) {
    	contactsRes.updateMapping();
    }
    
    @RequestMapping("/batdel")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView batdel(ModelMap map , HttpServletRequest request , HttpServletResponse response , @Valid String[] ids ,@Valid String ckind,@Valid String itemid) throws IOException {
    	if(ids!=null && ids.length > 0){
    		Iterable<Contacts> contactsList = contactsRes.findByIdInAndOrgi(Arrays.asList(ids),super.getOrgi(request)) ;
    		if(contactsList != null){
    			this.contactsRes.delete(contactsList);
    		}
//    		for(Contacts contacts :contactsList) {
//    			contacts.setDatastatus(true);	
//    		}
//    		this.contactsRes.save(contactsList);
    	}
    	
    	 return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html?p="+request.getParameter("p")+"&itemid="+itemid));
    }
    
    @RequestMapping("/item/add")
    @Menu(type = "contacts" , subtype = "add")
    public ModelAndView itemadd(ModelMap map , HttpServletRequest request,@Valid String addtype) {
    	map.addAttribute("contactsItemList", getContactsItem(super.getUser(request),super.getOrgi(request))) ;
    	map.addAttribute("addtype", addtype) ;
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/additem"));
    }
    
    @RequestMapping("/item/save")
    @Menu(type = "contacts" , subtype = "save")
    public ModelAndView itemsave(HttpServletRequest request  , @Valid ContactsItem contactsItem) {
    	ContactsItem item = null ;
    	if (!StringUtils.isBlank(contactsItem.getName())) {
    		item = new ContactsItem();
    		item.setCreater(super.getUser(request).getId());
    		item.setItemid(!StringUtils.isBlank(contactsItem.getParentid())?contactsItem.getParentid():item.getId());
    		item.setParentid(!StringUtils.isBlank(contactsItem.getParentid())?contactsItem.getParentid():null);
    		item.setName(contactsItem.getName());
    		item.setOrgi(super.getOrgi(request));
    		item.setStatuscode(contactsItem.getStatuscode());
//    		item.setType(UKDataContext.ContactsItemType.CONTACTS.toString());
    		contactsItemRes.save(item) ;
		}
    	String id = item!=null&&!StringUtils.isBlank(item.getParentid())?item.getId():"" ;
		return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html?itemid="+id));
    }
    
    @RequestMapping("/item/edit")
    @Menu(type = "contacts" , subtype = "add")
    public ModelAndView itemedit(ModelMap map , HttpServletRequest request,@Valid String id,@Valid String itemid) {
    	map.addAttribute("contactsItemList", getContactsItem(super.getUser(request),super.getOrgi(request))) ;
    	if (!StringUtils.isBlank(id)) {
			map.addAttribute("contactsItem", contactsItemRes.findByIdAndOrgi(id, super.getOrgi(request))) ;
		}
    	map.addAttribute("itemid", itemid) ;
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/edititem"));
    }
    
    @RequestMapping("/item/update")
    @Menu(type = "contacts" , subtype = "save")
    public ModelAndView itemupdate(HttpServletRequest request  , @Valid ContactsItem contactsItem ,@Valid String itemid) {
    	ContactsItem item = null ;
    	if (!StringUtils.isBlank(contactsItem.getId()) && !StringUtils.isBlank(contactsItem.getName())) {
    		item = contactsItemRes.findByIdAndOrgi(contactsItem.getId(), super.getOrgi(request));
    		item.setItemid(!StringUtils.isBlank(contactsItem.getParentid())?contactsItem.getParentid():item.getId());
    		item.setParentid(!StringUtils.isBlank(contactsItem.getParentid())?contactsItem.getParentid():null);
    		item.setName(contactsItem.getName());
    		item.setUpdatetime(new Date());
    		item.setStatuscode(contactsItem.getStatuscode());
    		contactsItemRes.save(item) ;
		}
    	String id = !StringUtils.isBlank(itemid)?itemid:item!=null?item.getId():"";
		return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html?itemid="+id));
    }
    
    @RequestMapping("/item/delete")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView itemdelete(HttpServletRequest request ,@Valid String itemid) {
    	if(!StringUtils.isBlank(itemid)){
    		ContactsItem item = contactsItemRes.findByIdAndOrgi(itemid, super.getOrgi(request)) ;
    		if (item != null) {
    			List<ContactsItem> contactsItems = contactsItemRes.findByParentidAndOrgi(itemid, super.getOrgi(request)) ;
    			contactsItems.add(item) ;
    			if (contactsItems != null && contactsItems.size() > 0) {
    				List<String> contactidList = new ArrayList<String>();
					for(ContactsItem contactsItem : contactsItems) {
						if (!StringUtils.isBlank(contactsItem.getId())) {
							contactidList.add(contactsItem.getId()) ;
						}
					}
					List<ContactsItemAuthorize> contactsItemAuthorizeList = contactsItemAuthorizeRes.findByItemidInAndOrgi(contactidList, super.getOrgi(request)) ;
					if (contactsItemAuthorizeList != null && contactsItemAuthorizeList.size() > 0) {
						contactsItemAuthorizeRes.delete(contactsItemAuthorizeList);
					}
					contactsItemRes.delete(contactsItems);
				}
			}
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html"));
    }
    
    @RequestMapping("/item/auth")
    @Menu(type = "contacts" , subtype = "add")
    public ModelAndView itemauth(ModelMap map , HttpServletRequest request,@Valid String id) {
    	List<Organ> organList = organRes.findByOrgiAndOrgid(super.getOrgiByTenantshare(request),super.getOrgid(request)) ;
    	List<String> organstrList = new ArrayList<String>() ;
    	if (organList != null && organList.size() > 0) {
			for(Organ organ : organList) {
				organstrList.add(organ.getId());
			}
		}
    	map.addAttribute("contactsItemAuthorizeList",contactsItemAuthorizeRes.findByItemidAndOrgiAndDatastatus(id, super.getOrgi(request),false));
    	map.addAttribute("userList", userRes.findByOrganInAndDatastatusAndOrgi(organstrList, false ,super.getOrgi(request)) );
    	map.addAttribute("organList", organList);
		map.addAttribute("id", id) ;
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/itemauth"));
    }
    
    @RequestMapping("/item/authsave")
    @Menu(type = "contacts" , subtype = "save")
    public ModelAndView authsave(HttpServletRequest request  , @Valid String id,@Valid String[] userid,@Valid String[] sup,@Valid String[] deluserid) {
    	if (!StringUtils.isBlank(id)) {
    		ContactsItem item = contactsItemRes.findByIdAndOrgi(id, super.getOrgi(request)) ;
    		if (item != null) {
    			List<ContactsItemAuthorize> tempContactsItemAuthorizeList = new ArrayList<ContactsItemAuthorize>();
    			if (deluserid != null && deluserid.length > 0) {
					List<ContactsItemAuthorize> delAuthorizes = contactsItemAuthorizeRes.findByUseridInAndItemidAndOrgiAndDatastatus(Arrays.asList(deluserid), id,  super.getOrgi(request),false) ;
					if (delAuthorizes != null && delAuthorizes.size() > 0) {
						for(ContactsItemAuthorize authorize : delAuthorizes) {
							authorize.setDatastatus(true);
							authorize.setCreater(super.getUser(request).getId());
							authorize.setCreatetime(new Date());
							tempContactsItemAuthorizeList.add(authorize);
						}
					}
				}
				if (userid != null && userid.length > 0) {
					List<User> userList = userRes.findByIdInAndOrgiAndDatastatus(Arrays.asList(userid), super.getOrgi(request), false) ;
					if (userList != null && userList.size() > 0) {
						for(User user : userList) {
							ContactsItemAuthorize cia = contactsItemAuthorizeRes.findByItemidAndUseridAndOrgi(item.getId(),user.getId(), super.getOrgi(request)) ;
							if (cia == null) {
								cia = new ContactsItemAuthorize();
							}
							cia.setDatastatus(false);
							cia.setCreater(super.getUser(request).getId());
							cia.setCreatetime(new Date());
							cia.setItemid(item.getId());
							cia.setOrgi(super.getOrgi(request));
							cia.setUserid(user.getId());
							cia.setSup(false);
							if (sup != null && sup.length > 0 && Arrays.asList(sup).contains(user.getId())) {
								cia.setSup(true);
							}
							tempContactsItemAuthorizeList.add(cia);
						}
					}
				}
				if (tempContactsItemAuthorizeList.size() > 0) {
					contactsItemAuthorizeRes.save(tempContactsItemAuthorizeList) ;
				}
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html?itemid="+id));
    }
    
    @RequestMapping("/item/user")
    @Menu(type = "callout" , subtype = "productcon")
    public ModelAndView itemuser(ModelMap map , HttpServletRequest request , @Valid String organ, @Valid String itemid) {
    	map.addAttribute("contactsItemAuthorizeList",contactsItemAuthorizeRes.findByItemidAndOrgiAndDatastatus(itemid, super.getOrgi(request),false));
    	map.addAttribute("userList", userRes.findByOrganAndDatastatusAndOrgi(organ, false, super.getOrgi(request)) );
    	return request(super.createRequestPageTempletResponse("/apps/business/contacts/userlist")) ; 
    }
    
    @RequestMapping("/view")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView view(ModelMap map , HttpServletRequest request ,final @Valid String id) {
    	final String orgi = super.getOrgi(request) ;
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	if(!StringUtils.isBlank(id)){
    		boolQueryBuilder.must(termQuery("id" , id)) ;
        }
    	Contacts contacts = null;
    	Page<Contacts> contactsPage = contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,null , new PageRequest(super.getP(request) , super.getPs(request))) ;
    	if (contactsPage != null  &&contactsPage.getContent().size() > 0) {
    		contacts = contactsPage.getContent().get(0);
		}
    	map.addAttribute("contacts", contacts) ;
    	if (contacts != null) {
    		ContactsItem contactsItem = contactsItemRes.findByIdAndOrgi(contacts.getItemid(), super.getOrgi(request)) ;
    		if (contactsItem != null) {
    			ContactsItemAuthorize authorize = contactsItemAuthorizeRes.findByItemidAndUseridAndOrgiAndDatastatus(contactsItem.getId(), super.getUser(request).getId(), super.getOrgi(request),false);
    			if ((authorize != null && authorize.isSup()) || contactsItem.getCreater().equals(super.getUser(request).getId())) {
    				map.addAttribute("isSup",true);
    			}
			}else {
				if (contacts.getCreater()!=null && contacts.getCreater().equals(super.getUser(request).getId())) {
					map.addAttribute("isSup",true);
				}
			}
    		
    		map.addAttribute("contactsItem", contactsItem) ;
    		//关系联系人
    		List<ContactsRelation> contactsRelationList = contactsRelationRes.findByContactsidAndOrgi(contacts.getId(), super.getOrgi(request));
    		if (contactsRelationList != null && contactsRelationList.size() > 0) {
    			List<String> idsList = new ArrayList<String>();
				for(ContactsRelation relation : contactsRelationList) {
					idsList.add(relation.getRelateid()) ;
				}
				if (idsList != null) {
					BoolQueryBuilder boolQueryBuilder2 = new BoolQueryBuilder();
					BoolQueryBuilder boolQueryBuilder3 = new BoolQueryBuilder();
					for(String ids : idsList) {
						boolQueryBuilder3.should(termQuery("id", ids)) ;
					}
					boolQueryBuilder2.must(boolQueryBuilder3);
					Page<Contacts> conPage = contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder2 ,null , new PageRequest(super.getP(request) , super.getPs(request)));
					map.addAttribute("relcontactsList",conPage ) ;
					map.addAttribute("contactsRelationList",contactsRelationList ) ;
				}
			}
    		
    		List<ContactsItem> resultList = new ArrayList<ContactsItem>();
    		List<ContactsItem> contactsItemList = getContactsItem(super.getUser(request),super.getOrgi(request));
    		if(!contactsItemList.isEmpty()){
    			for(ContactsItem contactsItemTemp :contactsItemList){
    				List<ContactsItem> dataList = contactsItemRes.findByParentidAndOrgi(contactsItemTemp.getId(), super.getOrgi(request));
    				if(!dataList.isEmpty()){
    					resultList.addAll(dataList);
    				}
    			}
    		}
    		map.addAttribute("contactsItemList", resultList) ;
    		
    		//通话历史
    		map.addAttribute("statusEventHisList",statusEventRes.findAll(new Specification<StatusEvent>(){
				@Override
				public Predicate toPredicate(Root<StatusEvent> root, CriteriaQuery<?> query,
						CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<Predicate>();  
					list.add(cb.equal(root.get("orgi").as(String.class), orgi));
					list.add(cb.equal(root.get("contactsid").as(String.class), id));
					Predicate[] p = new Predicate[list.size()];  
					return cb.and(list.toArray(p));  
				}},new PageRequest(super.getP(request),super.getPs(request),Sort.Direction.DESC,new String[] {"createtime"})));
    		
    		//会话历史
			Page<AgentService> agentServiceList = agentServiceRepository.findAll(new Specification<AgentService>() {
				@Override
				public Predicate toPredicate(Root<AgentService> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<Predicate>();  
					list.add(cb.equal(root.get("orgi").as(String.class), orgi));
					list.add(cb.equal(root.get("contactsid").as(String.class), id));
					Predicate[] p = new Predicate[list.size()];  
					return cb.and(list.toArray(p));  
				}
			}, new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC,new String[] {"createtime"}));
			map.addAttribute("agentServiceList", agentServiceList);
			map.addAttribute("contactsModel", true);
			
			//服务小结
			List<AgentServiceSummary> summaryList = this.serviceSummaryRes.findByOrgiAndContactsid(super.getOrgi(request), id);
			map.addAttribute("summaryList", summaryList) ;
			List<SysDic> reservtypeList = UKeFuDic.getInstance().getDic("com.dic.summary.reservtype");
			map.addAttribute("reservtypeList", reservtypeList);
			map.addAttribute("tags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.CCSUMMARY.toString())) ;
			
			//工单
			if(UKDataContext.model.get("workorders")!=null && !StringUtils.isBlank(contacts.getId())){
				if(workOrdersRes != null){
					map.addAttribute("workOrdersList", workOrdersRes.findByCusidAndOrgi(contacts.getId(), orgi)) ;
				}
				map.addAttribute("contactsid", contacts.getId()) ;
			}
			//名单
			BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
			queryBuilder.must(termQuery("contactsid", id));
			PageImpl<UKDataBean> dataList = SearchTools.search(super.search(queryBuilder, map, request), super.getP(request),
					super.getPs(request));
			map.addAttribute("dataallList", dataList);
			if (dataList.getContent().size() > 0) {
				HashSet<String> metaIdList = new HashSet<>();
				for(UKDataBean bean : dataList.getContent()) {
					String name = bean.getType() ;
					if(!StringUtils.isBlank(name)) {
						name = (String) bean.getValues().get("metaid") ;
					}
					if(!StringUtils.isBlank(name)) {
						metaIdList.add(name);
					}
				}
				if(metaIdList.size() > 0) {
					List<String> metaList = new ArrayList<>();
					metaList.addAll(metaIdList);
					List<MetadataTable> tableList = metadataRes
							.findByTablenameIn(metaList);
					map.put("tableList", tableList);
				}
			}
			//营销记录
			Page<CallOutNamesHis> hisPage =callOutNamesHisRes.findByDataidAndOrgi( id,super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC, "createtime"));
			map.addAttribute("callOutNamesHisList", hisPage);
			map.addAttribute("userList", this.userRes.findByOrgiAndDatastatus(orgi, false));
			map.addAttribute("saleStatusList", saleStatusRes.findByOrgi(orgi));
		}
        return request(super.createAppsTempletResponse("/apps/business/contacts/view"));
    }
    
    @RequestMapping("/summary/add")
    @Menu(type = "contacts" , subtype = "add" , access = false)
    public ModelAndView addSummary(ModelMap map , HttpServletRequest request , @Valid String contactsid) {
		map.addAttribute("tags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.CCSUMMARY.toString())) ;
		map.addAttribute("contactsid", contactsid);
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/summary/addsummary"));
    }
    @RequestMapping(value="/summary/add/save")  
	@Menu(type = "contacts", subtype = "summarysave")
    public ModelAndView saveSummary(ModelMap map , HttpServletRequest request , @Valid AgentServiceSummary summary , @Valid String contactsid){ 
    	if (!StringUtils.isBlank(contactsid)) {
			Contacts contacts = contactsRes.findByIdAndOrgi(contactsid,super.getOrgi(request));
			if (contacts != null) {
				summary.setOrgi(super.getOrgi(request));
				summary.setCreater(super.getUser(request).getId());
				summary.setCreatetime(new Date());
				summary.setContactsid(contactsid);
				summary.setChannel(UKDataContext.ChannelTypeEnum.WEBIM.toString());
				serviceSummaryRes.save(summary) ;
			}
		}
		List<AgentServiceSummary> summaryList = this.serviceSummaryRes.findByOrgiAndContactsid(super.getOrgi(request), contactsid);
		map.addAttribute("summaryList", summaryList) ;
		List<SysDic> reservtypeList = UKeFuDic.getInstance().getDic("com.dic.summary.reservtype");
		map.addAttribute("reservtypeList", reservtypeList);
		map.addAttribute("tags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.CCSUMMARY.toString())) ;
		return request(super.createRequestPageTempletResponse("/apps/business/contacts/summary/summarylist"));
    }
    @RequestMapping("/summary/edit")
    @Menu(type = "contacts" , subtype = "add" , access = false)
    public ModelAndView editSummary(ModelMap map , HttpServletRequest request , @Valid String contactsid, @Valid String id) {
		map.addAttribute("tags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.CCSUMMARY.toString())) ;
		map.addAttribute("contactsid", contactsid);
		AgentServiceSummary summary = serviceSummaryRes.findByIdAndOrgi(id, super.getOrgi(request));
		map.addAttribute("summary", summary);
		
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/summary/editsummary"));
    }
	@RequestMapping(value="/summary/edit/save")  
	@Menu(type = "apps", subtype = "summarysave")
    public ModelAndView saveEditSummary(ModelMap map , HttpServletRequest request , @Valid AgentServiceSummary summary , @Valid String contactsid ){ 
		if(!StringUtils.isBlank(summary.getId())){
			if (!StringUtils.isBlank(contactsid)) {
				Contacts contacts = contactsRes.findByIdAndOrgi(contactsid,super.getOrgi(request));
				if (contacts != null) {
					summary.setOrgi(super.getOrgi(request));
					summary.setCreater(super.getUser(request).getId());
					summary.setCreatetime(new Date());
					summary.setChannel(UKDataContext.ChannelTypeEnum.WEBIM.toString());
					serviceSummaryRes.save(summary) ;
				}
			}
			map.addAttribute("contactsid", contactsid);
		}
		List<AgentServiceSummary> summaryList = this.serviceSummaryRes.findByOrgiAndContactsid(super.getOrgi(request), contactsid);
		map.addAttribute("summaryList", summaryList) ;
		List<SysDic> reservtypeList = UKeFuDic.getInstance().getDic("com.dic.summary.reservtype");
		map.addAttribute("reservtypeList", reservtypeList);
		map.addAttribute("tags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.CCSUMMARY.toString())) ;
		
		return request(super.createRequestPageTempletResponse("/apps/business/contacts/summary/summarylist"));
    }
	
	
	@RequestMapping("/relate")
    @Menu(type = "contacts" , subtype = "relate")
    public ModelAndView relate(ModelMap map , HttpServletRequest request,@Valid String contactsid) {
		FilterCriteria filterCriteria = new FilterCriteria();
		map.addAttribute("contactsid", contactsid) ;
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, this.doIndex(map, request, null, null, null,filterCriteria ,null) ,null , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/addrelate"));
    }
	
	@RequestMapping("/relate/delete")
    @Menu(type = "contacts" , subtype = "relate")
    public ModelAndView relatedelete(ModelMap map , HttpServletRequest request,@Valid String id,@Valid String relateid) {
		if (!StringUtils.isBlank(id)) {
			List<ContactsRelation> relationlist = contactsRelationRes.findByContactsidAndRelateidAndOrgi(id,relateid, super.getOrgi(request)) ;
			if (relationlist != null && relationlist.size() > 0) {
				contactsRelationRes.delete(relationlist); 
			}
			List<ContactsRelation> contactsRelationList = contactsRelationRes.findByContactsidAndOrgi(id, super.getOrgi(request));
			if (contactsRelationList != null && contactsRelationList.size() > 0) {
				List<String> idsList = new ArrayList<String>();
				for(ContactsRelation relations : contactsRelationList) {
					idsList.add(relations.getRelateid()) ;
				}
				if (idsList != null) {
					BoolQueryBuilder boolQueryBuilder2 = new BoolQueryBuilder();
					BoolQueryBuilder boolQueryBuilder3 = new BoolQueryBuilder();
					for(String ids : idsList) {
						boolQueryBuilder3.should(termQuery("id", ids)) ;
					}
					boolQueryBuilder2.must(boolQueryBuilder3);
					Page<Contacts> conPage = contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder2 ,null , new PageRequest(super.getP(request) , super.getPs(request)));
					map.addAttribute("relcontactsList",conPage ) ;
					map.addAttribute("contactsRelationList",contactsRelationList ) ;
				}
			}
			map.addAttribute("contacts",contactsRes.findByIdAndOrgi(id,super.getOrgi(request))) ;
		}
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/include/relist"));
    }
	
	@RequestMapping("/contactslist")
    @Menu(type = "contacts" , subtype = "relate")
    public ModelAndView contactslist(ModelMap map , HttpServletRequest request,@Valid String contactsid,@Valid String itemid,@Valid String ckind,@Valid String q) {
		map.addAttribute("contactsid", contactsid) ;
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	if(!StringUtils.isBlank(q)){
			q = q.replaceAll("(OR|AND|NOT|:|\\(|\\))", "") ;
			boolQueryBuilder.must(QueryBuilders.boolQuery().must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND))) ;
        	map.put("q", q) ;
        }
    	if(!StringUtils.isBlank(ckind) && !ckind.equals("null")){
    		boolQueryBuilder.must(termQuery("ckind" , ckind)) ;
        	map.put("ckind", ckind) ;
        	map.put("ckinddic", UKeFuDic.getInstance().getDicItem(ckind)) ;
        }
    	
    	//得到有权限的项目
    	List<ContactsItem> contactsItemList = getContactsItem(super.getUser(request),super.getOrgi(request)) ;
    	map.addAttribute("contactsItemList", contactsItemList) ;
    	
    	if(!StringUtils.isBlank(itemid) && !itemid.equals("null")){
    		ContactsItem contactsItem = contactsItemRes.findByIdAndOrgi(itemid, super.getOrgi(request)) ;
    		if (contactsItem != null) {
				boolQueryBuilder.must(termQuery("itemid",contactsItem.getId()));
				ContactsItemAuthorize authorize = contactsItemAuthorizeRes.findByItemidAndUseridAndOrgiAndDatastatus(itemid, super.getUser(request).getId(), super.getOrgi(request),false);
				if ((authorize != null && authorize.isSup()) || contactsItem.getCreater().equals(super.getUser(request).getId())) {
					map.addAttribute("isSup",true);
				}
			}
        	map.addAttribute("contactsItem", contactsItem);
        	map.put("itemid", itemid) ;
        }else if (StringUtils.isBlank(q)) {
        	boolQueryBuilder.mustNot(QueryBuilders.wildcardQuery("itemid", "*"));
		}
		map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/include/contactlist"));
    }
    
    @RequestMapping("/relate/save")
    @Menu(type = "contacts" , subtype = "relate")
    public ModelAndView relatesave(HttpServletRequest request  ,ModelMap map , @Valid String contactsid,@Valid String relateid,@Valid String relation) {
    	if (!StringUtils.isBlank(contactsid) && !StringUtils.isBlank(relateid)) {
    		if (contactsRelationRes.countByContactsidAndRelateidAndOrgi(contactsid,relateid,super.getOrgi(request))==0) {
    			ContactsRelation contactsRelation = new ContactsRelation();
    			contactsRelation.setContactsid(contactsid);
    			contactsRelation.setCreater(super.getUser(request).getId());
    			contactsRelation.setCreatetime(new Date());
    			contactsRelation.setOrgi(super.getOrgi(request));
    			contactsRelation.setRelateid(relateid);
    			contactsRelation.setRelation(relation);
    			contactsRelationRes.save(contactsRelation);
			}
    		List<ContactsRelation> contactsRelationList = contactsRelationRes.findByContactsidAndOrgi(contactsid, super.getOrgi(request));
    		if (contactsRelationList != null && contactsRelationList.size() > 0) {
    			List<String> idsList = new ArrayList<String>();
				for(ContactsRelation relations : contactsRelationList) {
					idsList.add(relations.getRelateid()) ;
				}
				if (idsList != null) {
					BoolQueryBuilder boolQueryBuilder2 = new BoolQueryBuilder();
					BoolQueryBuilder boolQueryBuilder3 = new BoolQueryBuilder();
					for(String ids : idsList) {
						boolQueryBuilder3.should(termQuery("id", ids)) ;
					}
					boolQueryBuilder2.must(boolQueryBuilder3);
					Page<Contacts> conPage = contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder2 ,null , new PageRequest(super.getP(request) , super.getPs(request)));
					map.addAttribute("relcontactsList",conPage ) ;
					map.addAttribute("contactsRelationList",contactsRelationList ) ;
				}
			}
			map.addAttribute("contacts",contactsRes.findByIdAndOrgi(contactsid,super.getOrgi(request))) ;

		}
		return request(super.createRequestPageTempletResponse("/apps/business/contacts/include/relist"));
    }
    
    @RequestMapping("/callagentorgan/organ")
    @Menu(type = "callout" , subtype = "productcon")
    public ModelAndView callagentorganlist(ModelMap map , HttpServletRequest request , @Valid String organ, @Valid String activityid) {
    	
    	map.addAttribute("currentorgan",organ);
    	
//    	if(UKDataContext.model.get("sales")!=null){
//    		final List<String> organList = CallCenterUtils.getAuthOrgan(userRoleRes, callOutRoleRes, super.getUser(request));
//        	List<Organ> tempOrganList = organRes.findAll(organList) ;
//    		map.addAttribute("organList", tempOrganList);
//    	}else {
//    		List<Organ> tempOrganList = organRes.findByOrgi(super.getOrgi(request));
//    		map.addAttribute("organList", tempOrganList);
//		}
    	List<Organ> organList = organRes.findByOrgiAndOrgid(super.getOrgiByTenantshare(request),super.getOrgid(request)) ;
    	map.addAttribute("organList", organList);
    	return request(super.createRequestPageTempletResponse("/apps/business/contacts/callagentorgan")) ; 
    }
    
    @RequestMapping("/dis")
    @Menu(type = "contacts" , subtype = "dis")
    public ModelAndView dis(ModelMap map , HttpServletRequest request,@Valid String itemid,@Valid String ckind,@Valid String[] ids,@Valid String size,@Valid String filter,@Valid String organ) throws JsonParseException, JsonMappingException, IOException {
		map.addAttribute("itemid", itemid) ;
		map.addAttribute("ckind", ckind) ;
		map.addAttribute("size", size) ;
		if (!StringUtils.isBlank(organ)) {
			map.addAttribute("organ", organ) ;
		}
		map.addAttribute("ids", ids!=null&&ids.length>0?Arrays.asList(ids):null) ;
		if (!StringUtils.isBlank(itemid)) {
			List<ContactsItemAuthorize> contactsItemAuthorizeList = contactsItemAuthorizeRes.findByItemidAndOrgi(itemid, super.getOrgi(request)) ;
			if (contactsItemAuthorizeList != null && contactsItemAuthorizeList.size() > 0) {
				List<String> useridList = new ArrayList<String>();
				for(ContactsItemAuthorize authorize : contactsItemAuthorizeList) {
					if (!useridList.contains(authorize.getUserid())) {
						useridList.add(authorize.getUserid());
					}
				}
				if (!StringUtils.isBlank(organ)) {
					map.addAttribute("userList", userRes.findByIdInAndOrganAndDatastatusAndOrgi(useridList, organ, false ,super.getOrgi(request)));
				}else {
					map.addAttribute("userList", userRes.findByIdInAndOrgiAndDatastatus(useridList, super.getOrgi(request),false));
				}
			}
		}else {
			if (!StringUtils.isBlank(organ)) {
				map.addAttribute("userList", userRes.findByOrganAndOrgiAndDatastatus(organ, super.getOrgi(request), false)) ;
			}else {
				map.addAttribute("userList", userRes.findByOrgiAndDatastatus(super.getOrgi(request), false));
			}
		}
    	if (!StringUtils.isBlank(filter)) {
    		String filterstr = UKTools.decode(filter.replaceAll(" ", "+"), String.class) ;
    		ObjectMapper objectMapper = new ObjectMapper();  
    		FilterCriteria filterCriteria = objectMapper.readValue(filterstr, FilterCriteria.class) ;
			if (filterCriteria != null) {
				filterCriteria.setContactsids(ids!=null&&ids.length>0?Arrays.asList(ids):null);
				map.addAttribute("filter", UKTools.encode(UKTools.toJson(filterCriteria)));
			}
		}else {
			FilterCriteria filterCriteria = new FilterCriteria();
			if (!StringUtils.isBlank(itemid)) {
				filterCriteria.setItemid(itemid);
			}else if (!StringUtils.isBlank(ckind)) {
				filterCriteria.setCkind(ckind);
			}
			map.addAttribute("filter", UKTools.encode(UKTools.toJson(filterCriteria)));
		}
//    	if(UKDataContext.model.get("sales")!=null){
//    		final List<String> organList = CallCenterUtils.getAuthOrgan(userRoleRes, callOutRoleRes, super.getUser(request));
//        	List<Organ> tempOrganList = organRes.findAll(organList) ;
//    		map.addAttribute("organList", tempOrganList);
//    	}else {
//    		List<Organ> tempOrganList = organRes.findByOrgi(super.getOrgi(request));
//    		map.addAttribute("organList", tempOrganList);
//		}
    	List<Organ> organList = organRes.findByOrgiAndOrgid(super.getOrgiByTenantshare(request),super.getOrgid(request)) ;
    	map.addAttribute("organList", organList);
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/dis"));
    }
    
    @RequestMapping("/dis/save")
    @Menu(type = "contacts" , subtype = "dis")
    public ModelAndView dissave(ModelMap map , HttpServletRequest request,@Valid String itemid,@Valid String ckind,@Valid String filter,@Valid String[] userids,@Valid String[] organs,@Valid JobTask taskinfo,@Valid Boolean plantask) {
    	if (!StringUtils.isBlank(filter) && ((userids!= null && userids.length>0)||(organs!= null && organs.length>0)) ) {
    		JobDetail jobDetail = new JobDetail();
    		jobDetail.setName("联系人分配任务-"+UKTools.dateFormate.format(new Date()));
    		jobDetail.setOrgi(super.getOrgi(request));
    		jobDetail.setCreater(super.getUser(request).getId());
    		jobDetail.setCreatetime(new Date());
    		jobDetail.setOrgan(super.getUser(request).getOrgan());
    		jobDetail.setActid(UKDataContext.MetadataTableType.UK_CONTACTS.toString());
    		jobDetail.setJdbcurl(UKTools.decode(filter, String.class).replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", ""));
    		jobDetail.setActype(UKDataContext.ContactsJobDetailType.DIS.toString());
    		jobDetail.setTaskstatus(UKDataContext.TaskStatusType.READ.getType());
    		if (!StringUtils.isBlank(request.getParameter("disnum"))) {
    			jobDetail.setDisnum(Integer.parseInt(request.getParameter("disnum")));
    		}
    		DisTarget disTarget = new DisTarget();
    		if (userids!= null && userids.length>0) {
    			disTarget.setUseridList(Arrays.asList(userids));
			}
    		if (organs!= null && organs.length>0) {
    			disTarget.setOrganidList(Arrays.asList(organs));
			}
    		jobDetail.setArea(UKTools.toJson(disTarget));
    		jobDetail.setTasktype(UKDataContext.TaskType.CONTACTS.toString());
    		if(jobDetail != null){
    			try {
    				if(taskinfo.getRepeatJustTime()!=null && taskinfo.getRepeatJustTime() > 23) {
    					taskinfo.setRepeatJustTime(23);
    				}
    				jobDetail.setPlantask(plantask) ;
    				ObjectMapper mapper = new ObjectMapper();  
    				jobDetail.setTaskinfo(mapper.writeValueAsString(taskinfo));
    				DecimalFormat format = new DecimalFormat("00");
    				jobDetail.setStarttime(format.format(taskinfo.getRunBeginHour())+":"+format.format(taskinfo.getRunBeginMinute())+":"+format.format(taskinfo.getRunBeginSecond()));
    				if(taskinfo.getIsRepeat() && taskinfo.getRepeatJustTime() > 0) {
    					jobDetail.setEndtime(format.format((taskinfo.getRunBeginHour() + taskinfo.getRepeatJustTime()))+":"+format.format(taskinfo.getRunBeginMinute())+":"+format.format(taskinfo.getRunBeginSecond()));
    				}
    				if(plantask!=null && plantask.booleanValue()) {
    					jobDetail.setCronexp(UKTools.convertCrond(taskinfo));
    					/**
    					 * 设定触发时间
    					 */
    					jobDetail.setNextfiretime(new Date());
    					jobDetail.setNextfiretime(UKTools.updateTaskNextFireTime(jobDetail));
    					jobDetail.setPlantask(true);
    				}else {
    					jobDetail.setPlantask(false);
    					jobDetail.setCronexp(null);
    					jobDetail.setNextfiretime(null);
    				}
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    			jobRes.save(jobDetail) ;
    		}
		}
		return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html?itemid="+itemid+"&ckind="+ckind));
    }
    
    @RequestMapping("/recycle")
    @Menu(type = "contacts" , subtype = "dis")
    public ModelAndView recycle(ModelMap map , HttpServletRequest request,@Valid String itemid,@Valid String ckind,@Valid String filter,@Valid String[] userids,@Valid String[] organs,@Valid String[] ids) throws JsonParseException, JsonMappingException, IOException {
    	FilterCriteria filterCriteria = null;
    	if (!StringUtils.isBlank(filter)) {
    		String filterstr = UKTools.decode(filter.replaceAll(" ", "+"), String.class) ;
    		ObjectMapper objectMapper = new ObjectMapper();  
    		filterCriteria = objectMapper.readValue(filterstr, FilterCriteria.class) ;
			if (filterCriteria != null) {
				filterCriteria.setContactsids(ids!=null&&ids.length>0?Arrays.asList(ids):null);
			}
		}else {
			filterCriteria = new FilterCriteria();
			if (!StringUtils.isBlank(itemid)) {
				filterCriteria.setItemid(itemid);
			}else if (!StringUtils.isBlank(ckind)) {
				filterCriteria.setCkind(ckind);
			}
		}
    	if (filterCriteria != null) {
    		JobDetail jobDetail = new JobDetail();
    		jobDetail.setName("联系人回收任务-"+UKTools.dateFormate.format(new Date()));
    		jobDetail.setOrgi(super.getOrgi(request));
    		jobDetail.setCreater(super.getUser(request).getId());
    		jobDetail.setCreatetime(new Date());
    		jobDetail.setOrgan(super.getUser(request).getOrgan());
    		jobDetail.setActid(UKDataContext.MetadataTableType.UK_CONTACTS.toString());
    		jobDetail.setJdbcurl(UKTools.toJson(filterCriteria).replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", ""));
    		jobDetail.setActype(UKDataContext.ContactsJobDetailType.RECYCLE.toString());
    		jobDetail.setTasktype(UKDataContext.TaskType.CONTACTS.toString());
    		jobDetail.setTaskstatus(UKDataContext.TaskStatusType.READ.getType());
    		if (!StringUtils.isBlank(request.getParameter("size"))) {
    			jobDetail.setDisnum(Integer.parseInt(request.getParameter("size")));
    		}
    		jobRes.save(jobDetail) ;
		}
		return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html?itemid="+itemid+"&ckind="+ckind));
    }
    
    @RequestMapping("/reservation/add")
    @Menu(type = "contacts" , subtype = "add" , access = false)
    public ModelAndView addReservation(ModelMap map , HttpServletRequest request , @Valid String contactsid, @Valid String statusCode) {
		map.addAttribute("contactsid", contactsid);
		if (StringUtils.isBlank(statusCode)) {
			List<SysDic> sysDicList = UKeFuDic.getInstance().getDic("com.dic.callout.activity");
			if (sysDicList!= null && sysDicList.size() > 0 && sysDicList.get(0)!=null) {
				statusCode = sysDicList.get(0).getId();
			}
		}
		List<SaleStatusType> saleStatusTypeList = saleStatusTypeRes.findByOrgiAndActivityid(super.getOrgi(request),statusCode);
		map.addAttribute("saleStatusTypeList", saleStatusTypeList);
		map.put("statusCode", statusCode);
		List<SaleStatus> saleStatusList = saleStatusRes.findByOrgiAndActivityid(super.getOrgi(request), statusCode) ;
		map.addAttribute("saleStatusList", saleStatusList);
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/apdetail"));
    }
    @RequestMapping("/reservation/salestatuslist")
    @Menu(type = "contacts" , subtype = "add" , access = false)
    public ModelAndView salestatuslist(ModelMap map , HttpServletRequest request , @Valid String id) {
    	List<SaleStatus> saleStatusList = saleStatusRes.findByOrgiAndCate(super.getOrgi(request), id);
    	map.addAttribute("saleStatusList", saleStatusList);
    	return request(super.createRequestPageTempletResponse("/apps/business/contacts/include/salestatuslist"));
    }
    
    @RequestMapping("/reservation/edit")
    @Menu(type = "contacts" , subtype = "edit" , access = false)
    public ModelAndView editReservation(ModelMap map , HttpServletRequest request , @Valid String id, @Valid String statusCode) {
    	if (!StringUtils.isBlank(id)) {
    		if (StringUtils.isBlank(statusCode)) {
    			List<SysDic> sysDicList = UKeFuDic.getInstance().getDic("com.dic.callout.activity");
    			if (sysDicList!= null && sysDicList.size() > 0 && sysDicList.get(0)!=null) {
    				statusCode = sysDicList.get(0).getId();
    			}
			}
    		if (!StringUtils.isBlank(statusCode)) {
				List<SaleStatusType> saleStatusTypeList = saleStatusTypeRes.findByOrgiAndActivityid(super.getOrgi(request),statusCode);
				map.addAttribute("saleStatusTypeList", saleStatusTypeList);
				map.put("statusCode", statusCode);
				List<SaleStatus> saleStatusList = saleStatusRes.findByOrgiAndActivityid(super.getOrgi(request), statusCode) ;
		    	map.addAttribute("saleStatusList", saleStatusList);
				CallOutNamesHis callOutNamesHis = callOutNamesHisRes.findByIdAndOrgi(id, super.getOrgi(request));
				map.addAttribute("callOutNamesHis", callOutNamesHis);
				if (callOutNamesHis != null) {
					map.addAttribute("contactsid", callOutNamesHis.getDataid());
					if (!StringUtils.isBlank(callOutNamesHis.getWorkstatus())) {
						SaleStatus saleStatus = saleStatusRes.findByIdAndOrgi(callOutNamesHis.getWorkstatus(), super.getOrgi(request));
				    	map.addAttribute("currsaleStatus", saleStatus);
					}
				}
    		}
		}
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/apdetail"));
    }
    
    @RequestMapping(value="/reservation/add/save")  
	@Menu(type = "apps", subtype = "summarysave")
    public ModelAndView saveSummary(ModelMap map , HttpServletRequest request , @Valid String contactsid, @Valid String salestatus ,@Valid CallOutNamesHis callOutNamesHis){ 
		if(!StringUtils.isBlank(contactsid)){
			Contacts contacts = contactsRes.findByIdAndOrgi(contactsid,super.getOrgi(request)) ;
			if (contacts != null) {
				CallOutNamesHis callOutNames = null;
				if (!StringUtils.isBlank(callOutNamesHis.getId())) {
					callOutNames = callOutNamesHisRes.findByIdAndOrgi(callOutNamesHis.getId(), super.getOrgi(request)) ;
					callOutNames.setReservation(callOutNamesHis.isReservation());
					callOutNames.setOptime(callOutNamesHis.getOptime());
					callOutNames.setMemo(callOutNamesHis.getMemo());
					callOutNames.setOrgi(super.getOrgi(request));
					callOutNames.setUpdatetime(new Date());
					callOutNames.setWorkstatus(salestatus);
				}else {
					callOutNames = new CallOutNamesHis();
					callOutNames.setReservation(callOutNamesHis.isReservation());
					callOutNames.setOptime(callOutNamesHis.getOptime());
					callOutNames.setMemo(callOutNamesHis.getMemo());
					callOutNames.setOrgi(super.getOrgi(request));
					callOutNames.setCreatetime(new Date());
					callOutNames.setDataid(contactsid);
					callOutNames.setWorkstatus(salestatus);
					callOutNames.setCreater(super.getUser(request).getId());
				}
				contacts.setReservation(callOutNamesHis.isReservation());
				contacts.setApstatus(callOutNamesHis.isReservation()?"true":"false");
				contacts.setProcessed(false);
				contacts.setOptime(callOutNamesHis.getOptime());
				contacts.setSalestatus(salestatus);
				contacts.setSalesmemo(callOutNamesHis.getMemo());
				contacts.setUpdatetime(new Date());
				contacts.setUpdateuser(super.getUser(request).getId());
	    		contacts.setUpdateusername(super.getUser(request).getUsername());
				contactsRes.save(contacts);
				callOutNamesHisRes.save(callOutNames);
				CallOutUtils.processContactsStatus(contacts,super.getUser(request),contactsItemRes,contactsRes,ordersCommentRes,statusEventRes);
					
				map.addAttribute("contactsItem", contactsItemRes.findByIdAndOrgi(contacts.getItemid(), super.getOrgi(request)));
			}
			//营销记录
			Page<CallOutNamesHis> hisPage =callOutNamesHisRes.findByDataidAndOrgi( contactsid,super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC, "createtime"));
			map.addAttribute("callOutNamesHisList", hisPage);
			
		}
		return request(super.createRequestPageTempletResponse("/apps/business/contacts/apdetalist"));
    }
    
    @RequestMapping(value="/dyn/save")  
	@Menu(type = "apps", subtype = "summarysave")
    public ModelAndView dynsave(ModelMap map , HttpServletRequest request , @Valid String id,@Valid OrdersComment comment , @RequestParam(value = "files", required = false) MultipartFile[] files) throws IOException{ 
		if (!StringUtils.isBlank(id)) {
			Contacts contacts = contactsRes.findByIdAndOrgi(id,super.getOrgi(request)) ;
			if (contacts != null && comment!=null && !StringUtils.isBlank(comment.getContent())) {
				comment.setCreater(super.getUser(request).getId());
	    		comment.setOrgi(super.getOrgi(request));
	    		comment.setId(UKTools.getUUID());
    			comment.setDataid(contacts.getId());
	    		comment.setCreatetime(new Date());
	    		ordersCommentRes.save(comment) ;
	    		processAttachmentFile(files, contacts, request, comment.getId(), contacts.getId());
	    		
	    		contactsRes.save(contacts);
			}
    		map.addAttribute("contacts", contacts) ;
		}
		return request(super.createRequestPageTempletResponse("/apps/business/contacts/include/dynform"));
    }
    
    @RequestMapping("/dynlist")
    @Menu(type = "workorders" , subtype = "comments" , access = false)
    public ModelAndView dynlist(ModelMap map , HttpServletRequest request , @Valid String contactsid) {
    	
    	if (!StringUtils.isBlank(contactsid)) {
			BoolQueryBuilder boolQueryBuilderdy = QueryBuilders.boolQuery();
			BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
			myBuilder.must(termQuery("dataid" , contactsid)) ;
			myBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
			boolQueryBuilderdy.must(myBuilder) ;
			Page<OrdersComment> ordercommentPage =  ordersCommentRes.findByQuery(boolQueryBuilderdy, null , new PageRequest(super.getP(request), 3 , Direction.DESC , "createtime"));
			map.addAttribute("orderCommentList", ordercommentPage);
			map.addAttribute("attachmentFileList", attachementRes.findByModelidAndOrgi(contactsid, super.getOrgi(request))) ;
		}
    	
    	
    	return request(super.createRequestPageTempletResponse("/apps/business/contacts/include/dynlist"));
    }
    
    /**
     * 单条作废
     * @return
     */
    @RequestMapping("/waste")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView waste(HttpServletRequest request ,@Valid String id ,@Valid String p,@Valid String ckind,@Valid String itemid) {
    	this.viewwaste(request, id);
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/wasted.html?p="+p+"&ckind="+ckind+"&itemid="+itemid));
    }
    
    /**
     * 我的部门-单条领取
     * @return
     */
    @RequestMapping("/receive")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView receive(HttpServletRequest request ,@Valid String id ,@Valid String p,@Valid String ckind,@Valid String itemid) {
    	this.viewreceive(request, id);
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/disorgan.html?p="+p+"&ckind="+ckind+"&itemid="+itemid));
    }
    
    /**
     * 单条收回
     * @return
     */
    @RequestMapping("/rle")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView rle(HttpServletRequest request ,@Valid String id ,@Valid String p,@Valid String ckind,@Valid String itemid) {
    	this.viewrle(request, id);
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/disorgan.html?p="+p+"&ckind="+ckind+"&itemid="+itemid));
    }
    
    /**
     * 单条作废
     * @return
     */
    @RequestMapping("/view/waste")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView viewwaste(HttpServletRequest request ,@Valid String id ) {
    	if(!StringUtils.isBlank(id)){
    		Contacts contacts = contactsRes.findByIdAndOrgi(id,super.getOrgi(request)) ;
    		if (contacts != null) {
    			contacts.setStatus(UKDataContext.NamesDisStatusType.WASTE.toString());
    			contacts.setOwnerdept(null);
    			contacts.setOwneruser(null);
    			contacts.setUpdatetime(new Date());
    			contactsRes.save(contacts) ;
			}
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/view.html?id="+id));
    }
    
    /**
     * 我的部门-单条领取
     * @return
     */
    @RequestMapping("/view/receive")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView viewreceive(HttpServletRequest request ,@Valid String id ) {
    	if(!StringUtils.isBlank(id)){
    		Contacts contacts = contactsRes.findByIdAndOrgi(id,super.getOrgi(request)) ;
    		if (contacts != null) {
	    		contacts.setStatus(UKDataContext.NamesDisStatusType.DISAGENT.toString());
	    		contacts.setOwneruser(super.getUser(request).getId());
	    		contacts.setOwnerdept(null);
	    		contacts.setDistime(new Date());
				contacts.setDiscount(contacts.getDiscount()+1);
	    		contactsRes.save(contacts) ;
    		}
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/view.html?id="+id));
    }
    
    /**
     * 单条收回
     * @return
     */
    @RequestMapping("/view/rle")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView viewrle(HttpServletRequest request ,@Valid String id ) {
    	if(!StringUtils.isBlank(id)){
    		Contacts contacts = contactsRes.findByIdAndOrgi(id,super.getOrgi(request)) ;
    		if (contacts != null) {
    			contacts.setStatus(UKDataContext.NamesDisStatusType.NOT.toString());
    			contacts.setOwnerdept(null);
    			contacts.setOwneruser(null);
    			contacts.setUpdatetime(new Date());
    			contactsRes.save(contacts) ;
    		}
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/view.html?id="+id));
    }
    
    
    
    private void  processAttachmentFile(MultipartFile[] files , Contacts contacts, HttpServletRequest request  , String dataid , String modelid) throws IOException{
    	if(files!=null && files.length > 0){
    		//保存附件
    		boolean attachment = false ;
    		for(MultipartFile file : files){
    			if(file.getSize() > 0){			//文件尺寸 限制 ？在 启动 配置中 设置 的最大值，其他地方不做限制
    				String fileid = UKTools.md5(file.getBytes()) ;	//使用 文件的 MD5作为 ID，避免重复上传大文件
    				if(!StringUtils.isBlank(fileid)){
		    			AttachmentFile attachmentFile = new AttachmentFile() ;
		    			attachmentFile.setCreater(super.getUser(request).getId());
		    			attachmentFile.setOrgi(super.getOrgi(request));
		    			attachmentFile.setOrgan(super.getUser(request).getOrgan());
		    			attachmentFile.setDataid(dataid);
		    			attachmentFile.setModelid(modelid);
		    			attachmentFile.setModel(UKDataContext.ModelType.CONTACTS.toString());
		    			attachmentFile.setFilelength((int) file.getSize());
		    			if(file.getContentType()!=null && file.getContentType().length() > 255){
		    				attachmentFile.setFiletype(file.getContentType().substring(0 , 255));
		    			}else{
		    				attachmentFile.setFiletype(file.getContentType());
		    			}
		    			if(file.getOriginalFilename()!=null && file.getOriginalFilename().length() > 255){
		    				attachmentFile.setTitle(file.getOriginalFilename().substring(0 , 255));
		    			}else{
		    				attachmentFile.setTitle(file.getOriginalFilename());
		    			}
		    			if(!StringUtils.isBlank(attachmentFile.getFiletype()) && attachmentFile.getFiletype().indexOf("image") >= 0){
		    				attachmentFile.setImage(true);
		    			}
		    			attachment = true ;
		    			attachmentFile.setFileid(fileid);
		    			attachementRes.save(attachmentFile) ;
		    			FileUtils.writeByteArrayToFile(new File(path , "app/contacts/"+fileid), file.getBytes());
    				}
    			}
    		}
    		if(attachment == true) {
    			contacts.setAttachment(true);
    		}
    	}
    }
    
    /**
     * 拨打失败 - 全部联系人
     * @param map
     * @param request
     * @param q
     * @param ckind
     * @param itemid
     * @return
     */
    @RequestMapping("/callfaild")
    @Menu(type = "contacts" , subtype = "callfaild",name="callfaild")
    public ModelAndView callfaild(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid String itemid ,@Valid String workstatus ,@Valid String hangupcase ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria ,contactstype) ;
    	filterCriteria.setCallfaild(true);
    	boolQueryBuilder.must(termQuery("callstatus",UKDataContext.NameStatusTypeEnum.CALLED.toString())) ;
    	boolQueryBuilder.must(termQuery("workstatus", UKDataContext.NamesCalledEnum.FAILD.toString())) ;
    	if(!StringUtils.isBlank(hangupcase)){
			boolQueryBuilder.must(termQuery("hangupcase", hangupcase)) ;
			filterCriteria.setHangupcase(hangupcase);
    	}
    	map.addAttribute("contactsList", contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("hangupcase", hangupcase) ;
    	map.put("nowUrl", "/apps/contacts/callfaild") ;
        return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping("/quality")
    @Menu(type = "contacts" , subtype = "quality",name="quality")
    public ModelAndView quality(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind, @Valid final String itemid ,@Valid final String qualitystatus
    		,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, q, ckind, itemid,filterCriteria,contactstype) ;
    	
    	if("qualityowner".equals(qualitystatus)){
    		//我的质检
    		boolQueryBuilder.must(termQuery("owneruser", super.getUser(request).getId())) ;
    	}
    	
    	Page<Contacts> contactsList = contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)));
    	map.addAttribute("contactsList", contactsList) ;
    	map.put("filterCriteria", UKTools.encode(UKTools.toJson(filterCriteria))) ;
    	map.put("qualitystatus", qualitystatus) ;
    	return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
    }
    
    @RequestMapping(value = "/quality/index")
    @Menu(type = "contacts" , subtype = "quality",name="quality")
    public ModelAndView index(ModelMap map , HttpServletRequest request ,@Valid final String discaller , @Valid final String discalled ,@Valid final String qualitystatus, @Valid String ckind, @Valid final String itemid
    		, @Valid final String begin , @Valid final String end , @Valid final String direction, @Valid final String userid, @Valid final String organ
    		,@Valid final String ringdurbegin ,@Valid final String ringdurend ,@Valid final String incallbegin ,@Valid final String incallend
    		,@Valid final String record ,@Valid final String misscall ,@Valid final String calltype,@Valid final String recordbegin,@Valid final String recordend ,@Valid String contactstype) {
    	FilterCriteria filterCriteria = new FilterCriteria();
    	BoolQueryBuilder boolQueryBuilder = this.doIndex(map, request, null, ckind, itemid,filterCriteria ,contactstype) ;
    	Page<Contacts> contactsList = contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, boolQueryBuilder ,null , new PageRequest(super.getP(request) , 10000));
    	map.addAttribute("contactsList", contactsList) ;
    	map.put("qualitystatus", qualitystatus) ;
    	map.put("ckind", ckind) ;
    	map.put("itemid", itemid) ;
    	final String orgi = super.getOrgi(request);
		final String ownerid = super.getUser(request).getId();
		Page<StatusEvent> page = statusEventRes.findAll(new Specification<StatusEvent>(){
			@Override
			public Predicate toPredicate(Root<StatusEvent> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
				list.add(cb.equal(root.get("userid").as(String.class), ownerid)) ;
				
				if("qualitypass".equals(qualitystatus)){
					list.add(cb.equal(root.get("qualityresult").as(String.class), UKDataContext.QualityResult.PASS.toString())) ;
				}else if("qualityfaild".equals(qualitystatus)){
					list.add(cb.equal(root.get("qualityresult").as(String.class), UKDataContext.QualityResult.FAILD.toString())) ;
				}
				
				if(!StringUtils.isBlank(discaller)){
					list.add(cb.equal(root.get("discaller").as(String.class), discaller)) ;
				}
				if(!StringUtils.isBlank(discalled)){
					list.add(cb.equal(root.get("discalled").as(String.class), discalled)) ;
				}
				if(!StringUtils.isBlank(direction)){
					list.add(cb.equal(root.get("direction").as(String.class), direction)) ;
				}
				if(!StringUtils.isBlank(organ)){
					list.add(cb.equal(root.get("organ").as(String.class), organ)) ;
				}
				try {
					if(!StringUtils.isBlank(begin) && begin.matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
						list.add(cb.greaterThan(root.get("createtime").as(Date.class), UKTools.dateFormate.parse(begin))) ;
					}
					if(!StringUtils.isBlank(end) && end.matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
						list.add(cb.lessThan(root.get("createtime").as(Date.class), UKTools.dateFormate.parse(end))) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				//振铃时长
				if(!StringUtils.isBlank(ringdurbegin)){
					list.add(cb.greaterThan(root.get("ringduration").as(int.class), Integer.parseInt(ringdurbegin)*1000)) ;
				}
				if(!StringUtils.isBlank(ringdurend)){
					list.add(cb.lessThan(root.get("ringduration").as(int.class), Integer.parseInt(ringdurend)*1000)) ;
				}
				
				//通话时长
				if(!StringUtils.isBlank(incallbegin)){
					list.add(cb.greaterThan(root.get("duration").as(int.class), Integer.parseInt(incallbegin)*1000)) ;
				}
				if(!StringUtils.isBlank(incallend)){
					list.add(cb.lessThan(root.get("duration").as(int.class), Integer.parseInt(incallend)*1000)) ;
				}
				
				//录音时长
				if(!StringUtils.isBlank(recordbegin)){
					list.add(cb.greaterThan(root.get("recordtime").as(int.class), Integer.parseInt(recordbegin)*1000)) ;
				}
				if(!StringUtils.isBlank(recordend)){
					list.add(cb.lessThan(root.get("recordtime").as(int.class), Integer.parseInt(recordend)*1000)) ;
				}
				
				//是否录音
				if(!StringUtils.isBlank(record)){
					list.add(cb.equal(root.get("record").as(boolean.class), record)) ;
				}
				
				//是否漏话
				if(!StringUtils.isBlank(misscall)){
					list.add(cb.equal(root.get("misscall").as(boolean.class), misscall)) ;
				}
				
				//呼叫方向
				if(!StringUtils.isBlank(calltype)){
					list.add(cb.equal(root.get("calltype").as(String.class), calltype)) ;
				}
				
				
				Predicate[] p = new Predicate[list.size()];  
			    return cb.and(list.toArray(p));  
			}}, new PageRequest(super.getP(request), super.getPs(request) , Sort.Direction.DESC, "starttime")) ;
		map.addAttribute("statusEventList", page) ;
		CallCenterUtils.getCallCenterSearch(map, orgi, discaller, discalled, begin, end, direction, userid, organ, ringdurbegin, ringdurend, incallbegin, incallend, record, misscall, calltype, recordbegin, recordend);
		return request(super.createAppsTempletResponse("/apps/business/contacts/qcindex"));
    }
    
    @RequestMapping("/quality/add")
    @Menu(type = "contacts" , subtype = "add" , access = false)
    public ModelAndView addQuality(ModelMap map , HttpServletRequest request , @Valid String contactsid, @Valid String statusCode
    		,@Valid String ckind ,@Valid String itemid ,@Valid String qualitystatus,@Valid String eventid) {
		map.addAttribute("ckind", ckind);
		map.addAttribute("itemid", itemid);
		map.addAttribute("qualitystatus", qualitystatus);
		map.addAttribute("contactsid", contactsid);
		map.addAttribute("eventid", eventid);
		if(!StringUtils.isBlank(contactsid)){
			Contacts contacts = contactsRes.findByIdAndOrgi(contactsid,super.getOrgi(request));
			map.addAttribute("contacts", contacts);
			map.addAttribute("currsaleStatus", saleStatusRes.findByIdAndOrgi(contacts.getSalestatus(), super.getOrgi(request)));
		}
		if (StringUtils.isBlank(statusCode)) {
			List<SysDic> sysDicList = UKeFuDic.getInstance().getDic("com.dic.callout.activity");
			if (sysDicList!= null && sysDicList.size() > 0 && sysDicList.get(0)!=null) {
				statusCode = sysDicList.get(0).getId();
			}
		}
		List<SaleStatusType> saleStatusTypeList = saleStatusTypeRes.findByOrgiAndActivityid(super.getOrgi(request),statusCode);
		map.addAttribute("saleStatusTypeList", saleStatusTypeList);
		map.put("statusCode", statusCode);
		List<SaleStatus> saleStatusList = saleStatusRes.findByOrgiAndActivityid(super.getOrgi(request), statusCode) ;
		map.addAttribute("saleStatusList", saleStatusList);
		
		List<StatusEvent> statusEventList = this.statusEventRes.findByDataidAndOrgiAndQualityresultIsNull(contactsid ,super.getOrgi(request));
		map.addAttribute("statusEventList", statusEventList);
		if(!statusEventList.isEmpty()){
			StringBuffer str = new StringBuffer();
			for(StatusEvent statusEventTemp :statusEventList){
				str.append(",");
				str.append(statusEventTemp.getId());
			}
			map.addAttribute("statusEventIds", str);
		}
		
		//营销记录
		Page<CallOutNamesHis> hisPage =callOutNamesHisRes.findByDataidAndOrgi( contactsid,super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC, "createtime"));
		map.addAttribute("callOutNamesHisList", hisPage);
		map.addAttribute("userList", this.userRes.findByOrgiAndDatastatus(super.getOrgi(request), false));
		
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/qcdetail"));
    }
    @RequestMapping("/quality/calloutnamelist")
    @Menu(type = "contacts" , subtype = "add" , access = false)
    public ModelAndView addQualityCalloutnamelist(ModelMap map , HttpServletRequest request , @Valid String contactsid, @Valid String statusCode
    		,@Valid String ckind ,@Valid String itemid ,@Valid String qualitystatus,@Valid String eventid) {
    	List<SaleStatus> saleStatusList = saleStatusRes.findByOrgiAndActivityid(super.getOrgi(request), statusCode) ;
    	map.addAttribute("saleStatusList", saleStatusList);
    	//营销记录
    	Page<CallOutNamesHis> hisPage =callOutNamesHisRes.findByDataidAndOrgi( contactsid,super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC, "createtime"));
    	map.addAttribute("callOutNamesHisList", hisPage);
    	map.addAttribute("userList", this.userRes.findByOrgiAndDatastatus(super.getOrgi(request), false));
    	
    	return request(super.createRequestPageTempletResponse("/apps/business/contacts/calloutnamelist"));
    }
    
    @RequestMapping("/quality/add/save")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView saveQuality(HttpServletRequest request ,@Valid String ckind ,@Valid String itemid ,@Valid String eventids 
    		,@Valid String qualitystatus,@Valid String id ,@Valid String salestatus,@Valid String memo,@Valid String eventid ,@Valid String qualityresult) {
    	Contacts contacts = contactsRes.findByIdAndOrgi(id,super.getOrgi(request));
    	if(contacts != null){
    		//状态更新
    		contacts.setSalestatus(salestatus);
    		contacts.setSalesmemo(memo);
    		contacts.setUpdatetime(new Date());
    		contacts.setUpdateuser(super.getUser(request).getId());
    		contacts.setUpdateusername(super.getUser(request).getUsername());
    		contactsRes.save(contacts);
    		
    		CallOutUtils.processContactsStatus(contacts,super.getUser(request),contactsItemRes,contactsRes,ordersCommentRes,statusEventRes);
    		
    		//保存营销记录
    		CallOutNamesHis	callOutNames = new CallOutNamesHis();
			callOutNames.setMemo(memo);
			callOutNames.setOrgi(super.getOrgi(request));
			callOutNames.setCreatetime(new Date());
			callOutNames.setDataid(id);
			callOutNames.setWorkstatus(salestatus);
			callOutNames.setCreater(super.getUser(request).getId());
			this.callOutNamesHisRes.save(callOutNames);
    	}
    	
    	final String[] split = eventids.split(",");
    	final String orgi = super.getOrgi(request);
    	List<StatusEvent> statusEventList = null;
    	if (split != null && split.length > 0) {
    		statusEventList = statusEventRes.findAll(new Specification<StatusEvent>(){
    			@Override
    			public Predicate toPredicate(Root<StatusEvent> root, CriteriaQuery<?> query,
    					CriteriaBuilder cb) {
    				List<Predicate> list = new ArrayList<Predicate>();  
    				
    				list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
    				In<Object> inId = cb.in(root.get("id"));
    				if(split.length > 0){
    					for(String id : split){
    						if (!StringUtils.isBlank(id)) {
    							inId.value(id) ;
							}
    					}
    				}else{
    					inId.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
    				}
    				list.add(inId) ;
    				Predicate[] p = new Predicate[list.size()];  
    				return cb.and(list.toArray(p));  
    			}}) ;
		}
    	if(statusEventList != null && !statusEventList.isEmpty()){
    		List<StatusEvent> resultList = new ArrayList<>();
    		for(StatusEvent statusEventTemp :statusEventList){
    			//保存质检结果
    			statusEventTemp.setQualityresult(qualityresult);
        		resultList.add(statusEventTemp);
    		}
    		if(!resultList.isEmpty()){
    			this.statusEventRes.save(resultList);
    		}
    	}
    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/quality.html?ckind="+ckind+"&itemid="+itemid+"&qualitystatus="+qualitystatus));
    }
    
    
    
    
    @RequestMapping("/item/config")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView itemconfig(ModelMap map , HttpServletRequest request,@Valid String id) {
//    	map.addAttribute("ckind",ckind);
    	if (!StringUtils.isBlank(id)) {
			ContactsItem contactsItem = contactsItemRes.findByIdAndOrgi(id, super.getOrgi(request));
			if (contactsItem != null) {
				map.addAttribute("contactsItem",contactsItem);
				String statusCode = contactsItem.getStatuscode();
				if (StringUtils.isBlank(statusCode)) {
					List<SysDic> sysDicList = UKeFuDic.getInstance().getDic("com.dic.callout.activity");
					if (sysDicList!= null && sysDicList.size() > 0 && sysDicList.get(0)!=null) {
						statusCode = sysDicList.get(0).getId();
					}
				}
				List<SaleStatusType> saleStatusTypeList = saleStatusTypeRes.findByOrgiAndActivityid(super.getOrgi(request),statusCode);
				map.addAttribute("saleStatusTypeList", saleStatusTypeList);
				map.addAttribute("statusCode", statusCode);
				List<SaleStatus> saleStatusList = saleStatusRes.findByOrgiAndActivityid(super.getOrgi(request), statusCode) ;
				map.addAttribute("saleStatusList", saleStatusList);
				
				
				//用户
				List<User> userList = new ArrayList<User>();
				List<ContactsItemAuthorize> tempContactsItemAuthorizeList = contactsItemAuthorizeRes.findByItemidAndOrgi(id, super.getOrgi(request));
				if (tempContactsItemAuthorizeList != null && tempContactsItemAuthorizeList.size() > 0) {
					List<String> userIdList = new ArrayList<String>();
					 for(ContactsItemAuthorize contactsItemAuthorize: tempContactsItemAuthorizeList) {
						 if (!StringUtils.isBlank(contactsItemAuthorize.getUserid()) && !userIdList.contains(contactsItemAuthorize.getUserid())) {
							 userIdList.add(contactsItemAuthorize.getUserid());
						}
					 }
					 if (userIdList != null && userIdList.size() > 0) {
						 userList = userRes.findByIdInAndOrgiAndDatastatus(userIdList, super.getOrgi(request), false);
					}
				}
				userList.add(userRes.findBySuperuser(true));
				map.addAttribute("userList", userList);
				//部门
				List<Organ> organList = organRes.findByOrgiAndOrgid(super.getOrgiByTenantshare(request),super.getOrgid(request)) ;
		    	map.addAttribute("organList", organList);
		    	
		    	map.addAttribute("itemExpressList", contactsItem.getItemExpress());
			}
		}
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/itemconfig"));
    }
    
    @RequestMapping("/item/config/save")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView itemconfigsave(ModelMap map , HttpServletRequest request ,@Valid ContactsItem contactsItem,@Valid String[] distypes,@Valid String[] targetids,@Valid String[] status,@Valid String[] qualitys) throws IOException {
    	if (contactsItem != null && !StringUtils.isBlank(contactsItem.getId())) {
			ContactsItem item = contactsItemRes.findByIdAndOrgi(contactsItem.getId(), super.getOrgi(request));
			if (item != null) {
				item.setAutodis(contactsItem.isAutodis());
				item.setAutorecycle(contactsItem.isAutorecycle());
				item.setRecycletime(contactsItem.getRecycletime());
				if (status != null && status.length > 0 && distypes != null && distypes.length > 0 && targetids != null && targetids.length > 0&& qualitys != null && qualitys.length > 0) {
					List<ContactsItemExpress> contactsItemExpressList = new ArrayList<ContactsItemExpress>();
					List<ContactsItemTargetdis> contactsItemTargetdisList = item.getItemTargetdis();//原数据
					List<String> contactsItemTargetdisStrList = new ArrayList<String>();
					for(int i=0 ; i < status.length;i++) {
						ContactsItemExpress contactsItemExpress = new ContactsItemExpress();
						contactsItemExpress.setStatus(status[i]);
						contactsItemExpress.setDistype(distypes[i]);
						contactsItemExpress.setTargetid(Arrays.asList(targetids[i].split("，")));
						contactsItemExpress.setQuality(!StringUtils.isBlank(qualitys[i]) && (qualitys[i].equals("1")||qualitys[i].equals("true"))?true:false);
						contactsItemExpressList.add(contactsItemExpress);
					}
					List<String> targetidList = Arrays.asList(targetids);
					if (targetidList != null && targetidList.size() >0) {
					 	for(String targets : targetidList) {
					 		String[] targetid = targets.split(",");
					 		if (targetid != null && targetid.length > 0 ) {
								for(String tid : targetid) {
									contactsItemTargetdisStrList.add(tid);
								}
							}
					 	}
					}
					ContactsItemTargetdis contactsItemTargetdis ;
					if (contactsItemTargetdisList != null && contactsItemTargetdisList.size() > 0) {
						List<String> btargetdisstrList = new ArrayList<String>();//获取原来项目的目标id
						for(ContactsItemTargetdis contactsItemtargetdis :contactsItemTargetdisList) {
							if(!StringUtils.isBlank(contactsItemtargetdis.getTargetid())) {
								btargetdisstrList.add(contactsItemtargetdis.getTargetid()) ;
							}
						}
						if (contactsItemTargetdisStrList != null && contactsItemTargetdisStrList.size() > 0) {//获取原来项目的目标id
							for(String disStr : contactsItemTargetdisStrList) {
								if (!StringUtils.isBlank(disStr)) {
									if (!StringUtils.isBlank(disStr)) {
										String[] tids =disStr.split("，");
										if (tids != null && tids.length > 0 ) {
											for(String tidss : tids) {
												if (!btargetdisstrList.contains(tidss)) {
													contactsItemTargetdis = new ContactsItemTargetdis();
													contactsItemTargetdis.setDistimes(0);
													contactsItemTargetdis.setTargetid(tidss);
													contactsItemTargetdisList.add(contactsItemTargetdis) ;
												}
											}
										}
									}
								}
							}
						}
					}else {
						contactsItemTargetdisList = new ArrayList<ContactsItemTargetdis>();
						if (contactsItemTargetdisStrList != null && contactsItemTargetdisStrList.size() > 0) {
							for(String tid : contactsItemTargetdisStrList) {
								if (!StringUtils.isBlank(tid)) {
									String[] tids =tid.split("，");
									if (tids != null && tids.length > 0 ) {
										for(String tidss : tids) {
											contactsItemTargetdis = new ContactsItemTargetdis();
											contactsItemTargetdis.setDistimes(0);
											contactsItemTargetdis.setTargetid(tidss);
											contactsItemTargetdisList.add(contactsItemTargetdis) ;
										}
									}
								}
							}
						}
					}
					item.setTargetdis(UKTools.toJson(contactsItemTargetdisList).replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", ""));
					item.setExpress(UKTools.toJson(contactsItemExpressList).replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", ""));
				}else {
					item.setTargetdis(null);
					item.setExpress(null);
				}
				contactsItemRes.save(item);
			}
		}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html?itemid="+contactsItem.getId()));
    }
    
    public BoolQueryBuilder doFilterSearch(String q , String ckind, String itemid,FilterCriteria filterCriteria) {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	
     	if(!StringUtils.isBlank(q)){
			q = q.replaceAll("(OR|AND|NOT|:|\\(|\\))", "") ;
			boolQueryBuilder.must(QueryBuilders.boolQuery().must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND))) ;
        }
    	if(!StringUtils.isBlank(ckind) && !ckind.equals("null")){
    		boolQueryBuilder.must(termQuery("ckind" , ckind)) ;
        }
    	
    	if(!StringUtils.isBlank(itemid) && !itemid.equals("null")){
    		boolQueryBuilder.must(termQuery("itemid" , itemid)) ;
        }
    	
    	if(filterCriteria.getContactsids()!=null && filterCriteria.getContactsids().size() > 0) {
    		BoolQueryBuilder idsBooleanQueryBuilder = QueryBuilders.boolQuery();
    		for(String id : filterCriteria.getContactsids()) {
    			idsBooleanQueryBuilder.should(termQuery("id", id)) ;
    		}
    		boolQueryBuilder.must(idsBooleanQueryBuilder) ;
    	}
    	
    	//搜索条件
    	if(!StringUtils.isBlank(filterCriteria.getName())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("name",filterCriteria.getName())).should(QueryBuilders.wildcardQuery("name","*"+filterCriteria.getName()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCreater())) {
    		boolQueryBuilder.must(termQuery("creater", filterCriteria.getCreater())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCkind())) {
    		boolQueryBuilder.must(termQuery("ckind", filterCriteria.getCkind())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCkinds())) {
    		boolQueryBuilder.must(termQuery("ckind", filterCriteria.getCkinds())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getGender())) {
    		boolQueryBuilder.must(termQuery("gender", filterCriteria.getGender())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getPhone())) {
    		boolQueryBuilder.must(termQuery("phone", filterCriteria.getPhone())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getMobileno())) {
    		boolQueryBuilder.must(termQuery("mobileno", filterCriteria.getMobileno())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getEmail())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("email",filterCriteria.getEmail())).should(QueryBuilders.wildcardQuery("email","*"+filterCriteria.getEmail()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getAddress())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("address",filterCriteria.getAddress())).should(QueryBuilders.wildcardQuery("address","*"+filterCriteria.getAddress()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getProvince())) {
    		boolQueryBuilder.must(termQuery("province", filterCriteria.getProvince())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCity())) {
    		boolQueryBuilder.must(termQuery("city", filterCriteria.getCity())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getCtype())) {
    		boolQueryBuilder.must(termQuery("ctype", filterCriteria.getCtype())) ;
    	}
    	
    	//客户
    	if(!StringUtils.isBlank(filterCriteria.getCusname())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("cusname",filterCriteria.getCusname())).should(QueryBuilders.wildcardQuery("cusname","*"+filterCriteria.getCusname()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCusphone())) {
    		boolQueryBuilder.must(termQuery("cusphone", filterCriteria.getCusphone())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCusemail())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("cusemail",filterCriteria.getCusemail())).should(QueryBuilders.wildcardQuery("cusemail","*"+filterCriteria.getCusemail()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCusprovince())) {
    		boolQueryBuilder.must(termQuery("cusprovince", filterCriteria.getCusprovince())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCuscity())) {
    		boolQueryBuilder.must(termQuery("cuscity", filterCriteria.getCuscity())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getCusaddress())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("cusaddress",filterCriteria.getCusaddress())).should(QueryBuilders.wildcardQuery("cusaddress","*"+filterCriteria.getCusaddress()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getEkind())) {
    		boolQueryBuilder.must(termQuery("ekind", filterCriteria.getEkind())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getElevel())) {
    		boolQueryBuilder.must(termQuery("ekind", filterCriteria.getElevel())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getEsource())) {
    		boolQueryBuilder.must(termQuery("ekind", filterCriteria.getEsource())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getMaturity())) {
    		boolQueryBuilder.must(termQuery("maturity", filterCriteria.getMaturity())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getIndustry())) {
    		boolQueryBuilder.must(termQuery("industry", filterCriteria.getIndustry())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getCusvalidstatus())) {
    		boolQueryBuilder.must(termQuery("cusvalidstatus", filterCriteria.getCusvalidstatus())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getSalestatus())) {
    		boolQueryBuilder.must(termQuery("salestatus", filterCriteria.getSalestatus())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getStatus())) {
    		boolQueryBuilder.must(termQuery("status", filterCriteria.getStatus())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getReservation())) {
    		boolQueryBuilder.must(termQuery("reservation", filterCriteria.getReservation().equals("1")?true:false)) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getReservtype())) {
    		boolQueryBuilder.must(termQuery("reservtype", filterCriteria.getReservtype())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getSalesmemo())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("salesmemo",filterCriteria.getSalesmemo())).should(QueryBuilders.wildcardQuery("salesmemo","*"+filterCriteria.getSalesmemo()+"*"))) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getUpdateuser())) {
    		boolQueryBuilder.must(termQuery("updateuser", filterCriteria.getUpdateuser())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getBusiness())) {
    		boolQueryBuilder.must(termQuery("business", filterCriteria.getBusiness())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getBusmemo())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("busmemo",filterCriteria.getBusmemo())).should(QueryBuilders.wildcardQuery("busmemo","*"+filterCriteria.getBusmemo()+"*"))) ;
    	}
    	
    	RangeQueryBuilder rangeQuery = null ;
		//创建时间区间查询
		if(!StringUtils.isBlank(filterCriteria.getTouchtimebegin()) || !StringUtils.isBlank(filterCriteria.getTouchtimeend())){
			if(!StringUtils.isBlank(filterCriteria.getTouchtimebegin())) {
				try {
					rangeQuery = QueryBuilders.rangeQuery("touchtime").from(UKTools.dateFormate.parse(filterCriteria.getTouchtimebegin()).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(filterCriteria.getTouchtimeend()) ) {
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("touchtime").to(UKTools.dateFormate.parse(filterCriteria.getTouchtimeend()).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(filterCriteria.getTouchtimeend()).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
		rangeQuery = null ;
		if(!StringUtils.isBlank(filterCriteria.getIncallbegin()) || !StringUtils.isBlank(filterCriteria.getIncallend())){
			if(!StringUtils.isBlank(filterCriteria.getIncallbegin())) {
				rangeQuery = QueryBuilders.rangeQuery("incall").from(Long.parseLong(filterCriteria.getIncallbegin())*1000) ;
			}
			if(!StringUtils.isBlank(filterCriteria.getIncallend()) ) {
				if(rangeQuery == null) {
					rangeQuery = QueryBuilders.rangeQuery("incall").to(Long.parseLong(filterCriteria.getIncallend())*1000) ;
				}else {
					rangeQuery.to(Long.parseLong(filterCriteria.getIncallend())*1000) ;
				}
			}
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
		rangeQuery = null ;
		if(!StringUtils.isBlank(filterCriteria.getOptimebegin()) || !StringUtils.isBlank(filterCriteria.getOptimeend())){
			if(!StringUtils.isBlank(filterCriteria.getOptimebegin())) {
				try {
					rangeQuery = QueryBuilders.rangeQuery("optime").from(UKTools.dateFormate.parse(filterCriteria.getOptimebegin()).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(filterCriteria.getOptimeend()) ) {
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("optime").to(UKTools.dateFormate.parse(filterCriteria.getOptimeend()).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(filterCriteria.getOptimeend()).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
		rangeQuery = null ;
		if(!StringUtils.isBlank(filterCriteria.getUpdatetimebegin()) || !StringUtils.isBlank(filterCriteria.getUpdatetimeend())){
			if(!StringUtils.isBlank(filterCriteria.getUpdatetimebegin())) {
				try {
					rangeQuery = QueryBuilders.rangeQuery("updatetime").from(UKTools.dateFormate.parse(filterCriteria.getUpdatetimebegin()).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(filterCriteria.getUpdatetimeend()) ) {
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("updatetime").to(UKTools.dateFormate.parse(filterCriteria.getUpdatetimeend()).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(filterCriteria.getUpdatetimeend()).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
    	return boolQueryBuilder ;
	}
    
    public BoolQueryBuilder doIndex(String q , String ckind, String itemid ,FilterCriteria filterCriteria) {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
     	if(!StringUtils.isBlank(q)){
			q = q.replaceAll("(OR|AND|NOT|:|\\(|\\))", "") ;
			boolQueryBuilder.must(QueryBuilders.boolQuery().must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND))) ;
        }
    	if(!StringUtils.isBlank(ckind) && !ckind.equals("null")){
    		boolQueryBuilder.must(termQuery("ckind" , ckind)) ;
        }
    	
    	if(!StringUtils.isBlank(itemid) && !itemid.equals("null")){
    		boolQueryBuilder.must(termQuery("itemid" , itemid)) ;
        }
    	
    	if(filterCriteria.getContactsids()!=null && filterCriteria.getContactsids().size() > 0) {
    		BoolQueryBuilder idsBooleanQueryBuilder = QueryBuilders.boolQuery();
    		for(String id : filterCriteria.getContactsids()) {
    			idsBooleanQueryBuilder.should(termQuery("id", id)) ;
    		}
    		boolQueryBuilder.must(idsBooleanQueryBuilder) ;
    	}
    	
    	//搜索条件
    	if(!StringUtils.isBlank(filterCriteria.getName())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("name",filterCriteria.getName())).should(QueryBuilders.wildcardQuery("name","*"+filterCriteria.getName()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCreater())) {
    		boolQueryBuilder.must(termQuery("creater", filterCriteria.getCreater())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCkind())) {
    		boolQueryBuilder.must(termQuery("ckind", filterCriteria.getCkind())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCkinds())) {
    		boolQueryBuilder.must(termQuery("ckind", filterCriteria.getCkinds())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getGender())) {
    		boolQueryBuilder.must(termQuery("gender", filterCriteria.getGender())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getPhone())) {
    		boolQueryBuilder.must(termQuery("phone", filterCriteria.getPhone())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getMobileno())) {
    		boolQueryBuilder.must(termQuery("mobileno", filterCriteria.getMobileno())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getEmail())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("email",filterCriteria.getEmail())).should(QueryBuilders.wildcardQuery("email","*"+filterCriteria.getEmail()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getAddress())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("address",filterCriteria.getAddress())).should(QueryBuilders.wildcardQuery("address","*"+filterCriteria.getAddress()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getProvince())) {
    		boolQueryBuilder.must(termQuery("province", filterCriteria.getProvince())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCity())) {
    		boolQueryBuilder.must(termQuery("city", filterCriteria.getCity())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getCtype())) {
    		boolQueryBuilder.must(termQuery("ctype", filterCriteria.getCtype())) ;
    	}
    	
    	//客户
    	if(!StringUtils.isBlank(filterCriteria.getCusname())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("cusname",filterCriteria.getCusname())).should(QueryBuilders.wildcardQuery("cusname","*"+filterCriteria.getCusname()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCusphone())) {
    		boolQueryBuilder.must(termQuery("cusphone", filterCriteria.getCusphone())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCusemail())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("cusemail",filterCriteria.getCusemail())).should(QueryBuilders.wildcardQuery("cusemail","*"+filterCriteria.getCusemail()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCusprovince())) {
    		boolQueryBuilder.must(termQuery("cusprovince", filterCriteria.getCusprovince())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getCuscity())) {
    		boolQueryBuilder.must(termQuery("cuscity", filterCriteria.getCuscity())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getCusaddress())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("cusaddress",filterCriteria.getCusaddress())).should(QueryBuilders.wildcardQuery("cusaddress","*"+filterCriteria.getCusaddress()+"*"))) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getEkind())) {
    		boolQueryBuilder.must(termQuery("ekind", filterCriteria.getEkind())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getElevel())) {
    		boolQueryBuilder.must(termQuery("ekind", filterCriteria.getElevel())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getEsource())) {
    		boolQueryBuilder.must(termQuery("ekind", filterCriteria.getEsource())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getMaturity())) {
    		boolQueryBuilder.must(termQuery("maturity", filterCriteria.getMaturity())) ;
		}
    	if(!StringUtils.isBlank(filterCriteria.getIndustry())) {
    		boolQueryBuilder.must(termQuery("industry", filterCriteria.getIndustry())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getCusvalidstatus())) {
    		boolQueryBuilder.must(termQuery("cusvalidstatus", filterCriteria.getCusvalidstatus())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getSalestatus())) {
    		boolQueryBuilder.must(termQuery("salestatus", filterCriteria.getSalestatus())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getStatus())) {
    		boolQueryBuilder.must(termQuery("status", filterCriteria.getStatus())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getReservation())) {
    		boolQueryBuilder.must(termQuery("reservation", filterCriteria.getReservation().equals("1")?true:false)) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getReservtype())) {
    		boolQueryBuilder.must(termQuery("reservtype", filterCriteria.getReservtype())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getSalesmemo())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("salesmemo",filterCriteria.getSalesmemo())).should(QueryBuilders.wildcardQuery("salesmemo","*"+filterCriteria.getSalesmemo()+"*"))) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getUpdateuser())) {
    		boolQueryBuilder.must(termQuery("owneruser", filterCriteria.getUpdateuser())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getBusiness())) {
    		boolQueryBuilder.must(termQuery("business", filterCriteria.getBusiness())) ;
    	}
    	if(!StringUtils.isBlank(filterCriteria.getBusmemo())) {
    		boolQueryBuilder.must(new BoolQueryBuilder().should(QueryBuilders.matchPhraseQuery("busmemo",filterCriteria.getBusmemo())).should(QueryBuilders.wildcardQuery("busmemo","*"+filterCriteria.getBusmemo()+"*"))) ;
    	}
    	
    	RangeQueryBuilder rangeQuery = null ;
		//创建时间区间查询
		if(!StringUtils.isBlank(filterCriteria.getTouchtimebegin()) || !StringUtils.isBlank(filterCriteria.getTouchtimeend())){
			if(!StringUtils.isBlank(filterCriteria.getTouchtimebegin())) {
				try {
					rangeQuery = QueryBuilders.rangeQuery("touchtime").from(UKTools.dateFormate.parse(filterCriteria.getTouchtimebegin()).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(filterCriteria.getTouchtimeend()) ) {
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("touchtime").to(UKTools.dateFormate.parse(filterCriteria.getTouchtimeend()).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(filterCriteria.getTouchtimeend()).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
		rangeQuery = null ;
		if(!StringUtils.isBlank(filterCriteria.getIncallbegin()) || !StringUtils.isBlank(filterCriteria.getIncallend())){
			if(!StringUtils.isBlank(filterCriteria.getIncallbegin())) {
				rangeQuery = QueryBuilders.rangeQuery("incall").from(Long.parseLong(filterCriteria.getIncallbegin())*1000) ;
			}
			if(!StringUtils.isBlank(filterCriteria.getIncallend()) ) {
				if(rangeQuery == null) {
					rangeQuery = QueryBuilders.rangeQuery("incall").to(Long.parseLong(filterCriteria.getIncallend())*1000) ;
				}else {
					rangeQuery.to(Long.parseLong(filterCriteria.getIncallend())*1000) ;
				}
			}
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
		rangeQuery = null ;
		if(!StringUtils.isBlank(filterCriteria.getOptimebegin()) || !StringUtils.isBlank(filterCriteria.getOptimeend())){
			if(!StringUtils.isBlank(filterCriteria.getOptimebegin())) {
				try {
					rangeQuery = QueryBuilders.rangeQuery("optime").from(UKTools.dateFormate.parse(filterCriteria.getOptimebegin()).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(filterCriteria.getOptimeend()) ) {
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("optime").to(UKTools.dateFormate.parse(filterCriteria.getOptimeend()).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(filterCriteria.getOptimeend()).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
		rangeQuery = null ;
		if(!StringUtils.isBlank(filterCriteria.getUpdatetimebegin()) || !StringUtils.isBlank(filterCriteria.getUpdatetimeend())){
			if(!StringUtils.isBlank(filterCriteria.getUpdatetimebegin())) {
				try {
					rangeQuery = QueryBuilders.rangeQuery("updatetime").from(UKTools.dateFormate.parse(filterCriteria.getUpdatetimebegin()).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(filterCriteria.getUpdatetimeend()) ) {
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("updatetime").to(UKTools.dateFormate.parse(filterCriteria.getUpdatetimeend()).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(filterCriteria.getUpdatetimeend()).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
		if(rangeQuery!=null) {
			boolQueryBuilder.must(rangeQuery) ;
		}
    	return boolQueryBuilder ;
	}
    
    @RequestMapping("/search/del")
    @Menu(type = "contacts" , subtype = "dis")
    public ModelAndView searchDel(ModelMap map , HttpServletRequest request,@Valid String itemid,@Valid String ckind,@Valid String[] ids,@Valid String size,@Valid String filter,@Valid String organ ,@Valid String contactstype ,@Valid String q) throws JsonParseException, JsonMappingException, IOException {
		map.addAttribute("itemid", itemid) ;
		map.addAttribute("ckind", ckind) ;
		map.addAttribute("size", size) ;
		FilterCriteria filterCriteria = null;
    	if (!StringUtils.isBlank(filter)) {
    		String filterstr = UKTools.decode(filter.replaceAll(" ", "+"), String.class) ;
    		ObjectMapper objectMapper = new ObjectMapper();  
    		filterCriteria = objectMapper.readValue(filterstr, FilterCriteria.class) ;
			if (filterCriteria != null) {
				filterCriteria.setContactsids(ids!=null && ids.length > 0?Arrays.asList(ids):null);
			}
		}else {
			filterCriteria = new FilterCriteria();
			if (!StringUtils.isBlank(itemid)) {
				filterCriteria.setItemid(itemid);
			}else if (!StringUtils.isBlank(ckind)) {
				filterCriteria.setCkind(ckind);
			}
		}
    	if(!StringUtils.isBlank(contactstype)){
    		map.addAttribute("contactstype", contactstype);
    	}else{
    		map.addAttribute("contactstype", "index");
    	}
    	Page<Contacts> page = contactsRes.findByQueryAndOrgi(null,super.getOrgi(request), null , null , false, this.doIndex(q, ckind, itemid, filterCriteria) ,q , new PageRequest(0 , 10000));
    	if(page != null && !page.getContent().isEmpty()){
    		contactsRes.delete(page.getContent());
    	}
    	
   	 return request(super.createRequestPageTempletResponse("redirect:/apps/contacts/index.html?p="+request.getParameter("p")+"&itemid="+itemid));
    }
    
    @RequestMapping("/detail/edit")
    @Menu(type = "contacts" , subtype = "contacts")
    public ModelAndView editDetail(ModelMap map , HttpServletRequest request , @Valid String id
    		,@Valid String ckind,@Valid String itemid,@Valid String p ,@Valid String contactstype ,@Valid String nowUrl,@Valid String statuseventid,@Valid String ani) {
    	this.searchContactsItemList(map, id, request);
    	map.addAttribute("type", itemid) ;
    	map.addAttribute("ckind",ckind);
    	map.addAttribute("p",p);
    	map.addAttribute("contactstype",contactstype);
    	map.addAttribute("nowUrl",nowUrl);
    	map.addAttribute("statuseventid",statuseventid);
    	map.addAttribute("ani",ani);
        return request(super.createRequestPageTempletResponse("/apps/business/contacts/editdetail"));
    }
    
    @RequestMapping("/detail/update")
    @Menu(type = "contacts" , subtype = "embedupdate")
    public ModelAndView detail(ModelMap map , HttpServletRequest request  , @Valid Contacts contacts ,@Valid String statuseventid,@Valid String ani) {
    	Contacts data = contactsRes.findByIdAndOrgi(contacts.getId(),super.getOrgi(request)) ;
    	this.setContactsDicDetails(request, contacts);
    	if(data!=null){
    		this.updateContacts(contacts, data, request);
	    	contactsRes.save(data);
    	}
    	
        return request(super.createRequestPageTempletResponse("redirect:/apps/softphone/index.html?id="+statuseventid+"&ani="+ani));
    }
    
    public void updateContacts(Contacts contacts ,Contacts data, HttpServletRequest request){
    	
    	UKTools.copyProperties(contacts,data
				,new String[]{"calltime","firstcalltimes","calltimes","ringtime","succcall","faildcall","incall","discount","reservation","processed","attachment"});
    	List<PropertiesEvent> events = PropertiesEventUtils.processPropertiesModify(request, contacts , data , "id" , "orgi" , "creater" ,"createtime" , "updatetime") ;	//记录 数据变更 历史
    	if(events.size()>0){
    		String modifyid = UKTools.getUUID() ;
    		Date modifytime = new Date();
    		for(PropertiesEvent event : events){
    			event.setDataid(contacts.getId());
    			event.setCreater(super.getUser(request).getId());
    			event.setOrgi(super.getOrgi(request));
    			event.setModifyid(modifyid);
    			event.setCreatetime(modifytime);
    			propertiesEventRes.save(event) ;
    		}
    	}
    	data.setPinyin(PinYinTools.getInstance().getFirstPinYin(contacts.getName()));
    	if(StringUtils.isBlank(contacts.getCbirthday())) {
    		data.setCbirthday(null);
		}else {
			data.setCbirthday(contacts.getCbirthday());
		}
    	data.setUpdatetime(new Date());
    }
    
    public void setContactsDicDetails(HttpServletRequest request ,Contacts contacts){
    	List<SysDic> dicList = UKeFuDic.getInstance().getDic("com.dic.xiaoe.input");
    	if(dicList != null && !dicList.isEmpty()){
    		Map<String, String> hashMap = new HashMap<>();
    		for(SysDic sysDic: dicList){
    			hashMap.put(sysDic.getCode(), request.getParameter(sysDic.getCode()));
    		}
    		contacts.setExtinfo(UKTools.toJson(hashMap));
    	}
    }
}